一般项目中都会用到调用接口的功能,用来分布式开发,业务代码职责分配等提高工作效率。本项目中使用HttpURLConnection编写的工具类调用服务端的接口。
- 遇到的问题现象
当接口返回状态码是200的时候,可以正常获取到响应体,能正常读取接口的返回值。当接口返回状态码是500的时候,工具类直接抛出了IOException异常。导致拿到的响应体为空。
跟小伙伴沟通,当接口responseCode是500的时候是有响应内容的,通过使用postman测试,也验证了说法。postman种能拿到响应内容,提示500接口错误。
获取响应体的代码:
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
- 解决办法
怀疑是HttpURLConnection工具包中有这样的规则,不能通过InputStream拿到接口异常情况下的响应体,通过查找资料找到了方法。
当接口返回responseCode不是200的时候要通过getErrorStream获取响应的内容:
(HttpURLConnection的API文档)
https://www.apiref.com/java11-zh/java.base/java/net/HttpURLConnection.html#getErrorStream()
修改后代码增加一层判断如下:
int code = conn.getResponseCode();
r.put("responseCode",code);
System.out.println("-----接口响应code为:"+code);
if(code == HttpURLConnection.HTTP_OK){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}else{
System.err.println("-----接口响应错误,响应code为:"+code+" URL:"+requestUrl);
in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
}
这样使用conn.getErrorStream(),获取异常情况下的响应流,就能拿到响应内容了。
- 完整的HttoURLConnection接口请求工具类如下:
public static JSONObject sendPost(String requestUrl, String param, boolean isproxy, String proxyHost, int proxyPort) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
JSONObject r = new JSONObject();
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = null;
if (isproxy) {
@SuppressWarnings("static-access")
Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) url.openConnection(proxy);
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(param);
out.flush();
int code = conn.getResponseCode();
r.put("responseCode",code);
System.out.println("-----接口响应code为:"+code);
if(code == HttpURLConnection.HTTP_OK){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}else{
System.err.println("-----接口响应错误,响应code为:"+code+" URL:"+requestUrl);
in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
}
String line;
while ((line = in.readLine()) != null) {
result += line;
}
r.put("data",result);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return r;
}