在Java中检索服务器端HTTP错误消息

时间:2016-12-16 14:55:04

标签: java api http error-handling server-side

我正在构建一个后端服务器端java应用程序,它使用post方法将数据发送到API,基于我在Python和C#(控制台应用程序)中给出的示例。此API具有与各种响应代码相关联的特定响应。我尝试使用下面的代码,但响应消息似乎是与响应代码关联的通用系统消息,而不是我正在访问的API上的消息。

 System.out.println("Response Code : " + connection.getResponseCode());
 System.out.println("Response Message : " + connection.getResponseMessage());

我在C#示例中看到他们正在使用WebException错误处理,但我找不到Java等价物,如果有的话。

编辑:这是我用403获得的错误,在python示例中,它返回了自定义响应

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://[redacted]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1926)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1921)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1920)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1490)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:59)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.rentrak.com/tv/v3/national_airing_views
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:56)

这是我用来构建响应的代码

    StringBuilder response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream()))) {
        String inputLine;
        response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }

1 个答案:

答案 0 :(得分:1)

如果您只使用java.net.HttpURLConnection

成功响应有connection.getInputStream()来获取响应正文。

但是对于错误响应,有connection.getErrorStream()错误响应正文。

我的意思是作为示例服务器返回HTTP 404 - 未找到自定义HTML页面的错误。 该HTML将位于错误流中而不是输入流中。

当然,响应代码在connection.getResponseCode()中为int(即404),响应消息在getResponseMessage()中(即"未找到")