3

I have a Groovy script that uses URLConnection to process a GET request (in this case it's to get an authentication token);

URLConnection loginURI = new URL("www.myaddress.fish").openConnection();
loginURI.setRequestProperty("Authorization","me:you");
response = loginURI.getInputStream();

Nothing complex, and this code works fine when the response is a 200 or similar. The response contains the details I need to progress.

However, sometimes the response is a 4xx response (most common is 400 Bad Request from an invalid Authorization header), and from running the same request through SOAPUI or similar I can see that the response body contains useful information (EG 'your username is incorrect'). I want to be able to capture that useful information for processing, but I'm not sure how to do it.

I've tried the traditional 'try/catch' idea, but I get the Java exception rather than the response body. Foolishly I tried a bog standard

println response.text

In the catch segment, but that didn't work at all. Assuming the response body is stored somewhere, how can I read it?

Slimy43
  • 341
  • 4
  • 17

1 Answers1

6

Looks like the error I was seeing wasn't because of the 4xx response, it was because getInputStream() isn't valid when the request has returned an error code. What I've done now is request the responseCode first (which always exists) then depending on what the code is will depend on whether I getInputStream() or getErrorStream().

In my case I've changed the code to;

responseCode=loginURI.getResponseCode();
if(responseCode != 200){
    response = loginURI.getErrorStream();
}else{
    response = loginURI.getInputStream();
}
println "login response:" + response.text;

I could probably change the If statement to be a bit more accurate (200 isn't the only valid response), but as I'm only interested in 200 being valid then it works for me.

Slimy43
  • 341
  • 4
  • 17