因为是做保险行业的,前段时间做了一个需求,要对接车险平台,用http方式请求数据,但是返回结果提示无数据,很纠结,因为用Postman测试的时候是有数据的,而且用java http包配合IO流写的方法是可以查询到数据的,后来经过尝试发现,可能是请求数据的时候没有指定正确的编码方式导致的,试了一下果然如此,所以跟大家分享一下,不多废话,上代码。
public static JSONObject sendHttpPost(String body,String uri) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Connection", "Keep-Alive");
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(body,"UTF-8"));//指定发送数据的编码方式(关键)
//设置连接超时时间,设置从connect Manager获取Connection 超时时间,请求获取数据的超时时间,单位毫秒。
// 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
JSONObject object = JSON.parseObject(responseContent);
response.close();
httpClient.close();
return object;
}