问题
今天通过HttpUtilClient调用接口,接收端中文成了“??”,找了好多文章都没解决,最后发现老项目里面有类似的代码,复制过来问题解决。
代码实现
请求端
// 参数为实体,用Gson转成字符串
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
HttpUtilClient.doPostJson("自己的接口",gson.toJson(entity));
// 对应的doPostJson方法
public static String doPostJson(String url, String json) {
//采用绕过验证的方式处理https请求
SSLContext sslcontext = null;
try {
sslcontext = createIgnoreVerifySSL();
} catch (KeyManagementException e1) {
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
//设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity = new StringEntity(json,"utf-8");
entity.setContentType("text/json");
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
接收端
@RequestMapping(value = "/url")
public Result<Boolean> saveAlarm(@RequestBody Entity entity){
// 业务逻辑
return RetResponse.ok();
}