Read error response body in Java

后端 未结 8 1357
暗喜
暗喜 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:23

    First check the response code and then use HttpURLConnection.getErrorStream()

    0 讨论(0)
  • 2020-11-28 06:23

    How to read 404 response body in java:

    Use Apache library - https://hc.apache.org/httpcomponents-client-4.5.x/httpclient/apidocs/

    or Java 11 - https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html

    Snippet given below uses Apache:

    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.util.EntityUtils;
    
    CloseableHttpClient client = HttpClients.createDefault();
    CloseableHttpResponse resp = client.execute(new HttpGet(domainName + "/blablablabla.html"));
    String response = EntityUtils.toString(resp.getEntity());
    
    0 讨论(0)
提交回复
热议问题