今天修改sonar里的bug时候发现,有个同事的代码,为了使用一个小方法,不知道从哪里复制了三个工具类进来,这两个工具类在sonar里面疯狂爆红,无奈之下,想给他把这三个工具类优化掉,从而碰见了一系列离奇的bug,特此记录。
从上图看出,该同事想通过java HttpClient对接口进行调用,实际上项目引入了hutool的工具包,只要使用hutool工具包即可。从代码记录中看出,该同事使用了如下代码进行测试:
HttpSession session = new HttpSession();
HttpClientResult httpClientResult = session.doGet(path, headers, params);
String content = httpClientResult.getContent();
JSONObject jsonObject = JSONObject.parseObject(content);
System.out.println("jsonObject === " + jsonObject);
if ("200".equals(jsonObject.getString("code"))) {
JSONObject result = JSONObject.parseObject(jsonObject.getString("result"));
String token = result.getString("token");
System.out.println("token === " + token);
}
System.out.println("================================================================");
/*String result = HttpRequest.get(path).headerMap(headers, true)
.contentType("application/json;charset=utf-8")
.form("username", username)
.form("password", pdw)
.setConnectionTimeout(2000)
.timeout(5000)
.execute().body();
System.out.println("result =============" + result);
JSONObject jsonObject1 = JSONObject.parseObject(result);
String resultCode = jsonObject1.getString("code");
if ("200".equals(resultCode)) {
JSONObject resultJson = JSONObject.parseObject(jsonObject1.getString("result"));
System.out.println("token === " + resultJson.get("token"));
}*/
可以看出,该同事想使用hutool工具类进行调用,但是注释了,当时我很好奇,为什么要注释掉然后使用自己的工具类进行调用呢,然后我就放开了自己测试了一下,后面发现使用hutool工具类调用的无法正常返回。hutool调用接口返回如下:
我决定弄清楚真相,然后我配好Fiddler对请求进行了抓包,看下两种请求有什么不一样,然HttpClient报了一个很奇怪的错:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException从字面上看是证书错误,百度之后找到一种快捷的解决办法,改变一下httpclient的创建方式就可以解决:
SSLContext sslContext = null;
try{
sslContext = SSLContexts.custom()
.loadTrustMaterial(null,(x509Certificates, s) -> true)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
CloseableHttpClient httpClient = HttpClients
.custom()
.setSslcontext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
后面通过抓包发现是一个参数url编码转换有问题
原来是 HttpClient默认对特殊字符串进行了编码,hutool工具类没有,修改完,接着测试,hutool工具类调用返回正常了,至此问题解决