尝试读取http连接响应时出现IOException

时间:2014-07-15 22:15:07

标签: java http ioexception

我正在Java通过Websphere Portlet提交以下请求 当我使用postman(Chrome扩展程序)手动提交但无法通过java将其设置为成功时,它可以正常工作。
我错过了什么?

我将远程主机的SSL证书导入Websphere,因此SSL连接不是问题 日志中的例外情况..

[7/15/14 23:06:39:993 BST] 00000170 ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service CWSRV0014E: Uncaught service() exception root cause MyApp: java.io.IOException: Server returned HTTP response code: 500 for URL: https://server.com/msg

这是调用请求并尝试读取响应的java代码。

URL url = new URL("https://server.com/msg");
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);

String body = URLEncoder.encode("{\"x\": \"hello\"}", "UTF-8");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(body);
out.close();

// Exception occurs here ..
BufferedReader rd2 = new BufferedReader(new InputStreamReader(connection.getInputStream()));

while ((line = rd2.readLine()) != null) {
    result += line;
}
rd2.close();

1 个答案:

答案 0 :(得分:0)

这是解决方案,而不是URLEncoder.encode() POST身体......

URL url = new URL(queries.getQuery(sessionBean.getSelectedQuery()));
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);

String json = "{\"x\": \"hello\"}";

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(json);
out.close();

BufferedReader rd2 = new BufferedReader(new InputStreamReader(connection.getInputStream()));

while ((line = rd2.readLine()) != null) {
    result += line;
}
rd2.close();