Read error response body in Java

后端 未结 8 1434
暗喜
暗喜 2020-11-28 05:32

In Java, this code throws an exception when the HTTP result is 404 range:

URL url = new URL(\"http://stackoverflow.com/asdf404notfound\");
HttpURLConnection          


        
8条回答
  •  盖世英雄少女心
    2020-11-28 06:06

    It's the same problem I was having: HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
    You should instead use getErrorStream() when the status code is higher than 400.

    More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.

    Here is an example of how I went to manage it

    ... connection code code code ...
    
    // Get the response code 
    int statusCode = connection.getResponseCode();
    
    InputStream is = null;
    
    if (statusCode >= 200 && statusCode < 400) {
       // Create an InputStream in order to extract the response object
       is = connection.getInputStream();
    }
    else {
       is = connection.getErrorStream();
    }
    
    ... callback/response to your handler....
    

    In this way, you'll be able to get the needed response in both success and error cases.

    Hope this helps!

提交回复
热议问题