getErrorStream: stream closed, getInputStream: works



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

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.getErrorStream() 替换conn.getInputStream(),我会得到一个

线程"main"java.io.IOException中的异常:流关闭

怎么来了?

我不确定,但是:

请确保

searchUrlPOST.replace("%accessToken", accessToken)

返回一个有效的 URL,此错误可以通过在"new Url(字符串 url)"中使用无效 URL 引发

最新更新