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?