getErrorStream: stream closed, getInputStream: works

流过昼夜 提交于 2019-12-11 18:08:44

问题


I have a weird issue with my code:

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());

That works perfectly fine as long as the server is responding with a proper status code. If he however responds with something like a 400 and i replace the conn.getInputStream() with a conn.getErrorStream() I get a

Exception in thread "main" java.io.IOException: Stream closed

How come?


回答1:


I'm not sure but:

Please make sure that

searchUrlPOST.replace("%accessToken", accessToken)

returns a valid url, this error can been thrown by using an invalid url at "new Url(String url)"



来源:https://stackoverflow.com/questions/35071191/geterrorstream-stream-closed-getinputstream-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!