HttpURLConnection:如何读取400响应的有效负载

use*_*796 5 java json httpurlconnection ioexception payload

我使用以下代码将JSON请求发送到我的Web服务,对于错误的请求,我返回了400消息代码以及有效负载中的详细JSON错误响应。

我不明白在使用时如何在客户端上检索此有效负载HttpURLConnection,因为它会立即引发IOException和连接InputStreamnull

HttpURLConnection connection = this.connect(url);
connection.setRequestMethod(method);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonMessage);
InputStream is = null;
try {
    is = connection.getInputStream(); // IOException is thrown, how can I still get payload??
} catch (Exception e) {
} 
String response = getStringFromInputStream(is);
Run Code Online (Sandbox Code Playgroud)

也尝试使用getErrorStream(),但这包含Apache Tomcat的默认错误页面,而不是我在例如使用可视REST API客户端时看到的有效负载。

use*_*796 -1

我发现许多线程指出,如果状态代码是错误消息,则 HTTPUrlConnection 根本不会传输标准负载,例如stackoverflow.com/questions/21526082/ \xe2\x80\xa6,如果有tbray ,也请参阅此博客.org/ongoing/When/201x/2012/01/17/HttpURLConnection

\n\n

我最终使用了更强大的 Apache 包。

\n

  • 当使用 java.net.HttpURLConnection 并收到错误响应代码时,您无法使用 getInputStream() 读取正文 在这种情况下,您必须使用 getErrorStream() 读取正文 (17认同)
  • 你还没有发现这样的事情。至少您引用的线程没有这么说。[这个答案](http://stackoverflow.com/a/21529527/207421)提供了解决方案。 (2认同)