getErrorStream:stream closed,getInputStream:works

时间:2016-01-28 20:17:28

标签: java stream httpconnection

我的代码有一个奇怪的问题:

URL url = new URL(searchUrlPOST.replace("%accessToken", accessToken));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");

OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();

// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());

只要服务器使用正确的状态代码进行响应,那就完美无缺。然而,如果他用400之类的东西做出回应,我用conn.getInputStream()替换conn.getErrorStream()我得到了

  

线程中的异常" main" java.io.IOException:Stream closed

怎么回事?

1 个答案:

答案 0 :(得分:0)

我不确定但是:

请确保

  

searchUrlPOST.replace(“%accessToken”,accessToken)

返回一个有效的网址,在“新网址(字符串网址)”中使用无效的网址可能会引发此错误