ekiyanov
ekiyanov

Reputation: 461

How to get a response body while getting 403. Java

I make a request to my web app, web app reports some errors. nothing complicated. just like this:

{"password":["can't be blank"]}

and it returns it with code 403.

In my android app I use HttpURLConnection to make a request and I catch an exception white trying to getInputStream.

In that exception I can getResponseMessage(), but all I got is 'Forbidden'

How can I get an actual response body?

HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0");
try {
    String result = IOUtils.toString(urlConnection.getInputStream());
    urlConnection.disconnect();
    App.SaveToken(result);
}catch(IOException exception){
    if (urlConnection.getResponseCode()==403)
    {
        return urlConnection.getResponseMessage();
    }
}

Upvotes: 2

Views: 1838

Answers (1)

Bidhan
Bidhan

Reputation: 10697

If the response code is not 200(or 2xx), use getErrorStream() instead of getInputStream().

Upvotes: 8

Related Questions