背景:
使用HttpURLConnection写的一个HttpUtil工具类,在正常访问到接口不会有问题,但是在异常的场景中,比如401,400,505等场景中会返回IO异常,而不是原来接口返回的 401,400,502等的接口返回信息
Returns the error stream if the connection failed but the server sent useful data nonetheless.
原来通过这个方法我们才能获取到responseCode不为200时(connection failed)的响应内容(useful data)!
原因:
如果getResponseCode不等于200,还是使用con.getInputStream()获取返回值,会导致IO异常,导致异常信息被替换为IO异常
解决方法:
根据responseCode来获取输入流,此处错误响应码的响应体内容也要获取
InputStream inputStream;
//根据responseCode来获取输入流,此处错误响应码的响应体内容也要获取(看服务端的返回结果形式决定)
if (HttpURLConnection.HTTP_OK == con.getResponseCode()) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
参考:https://blog.csdn.net/Abysscarry/article/details/82670748