原因:再做接口自动化测试过程中,发现发送POST请求时,请求成功后,新增的角色描述有中文,新增成功后出现乱码。
解决方法:在POST方法初始化StringEntity时指定UTF-8
原来代码如下:
public static HttpClientResult doPost(String url, String jsonstr,String token) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse=null;
String result="";
try {
//1.创建httpClient对象
//httpClient = HttpClients.createDefault();
httpClient =createHttpsClient(filePath,passWord);
//2.创建httpPost对象
HttpPost httpPost = new HttpPost(url);
//2.1对象设置请求头
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setHeader("Authorization",token);
//2.2对象设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
httpPost.setConfig(requestConfig);
//2.3对象设置请求参数
//httpPost.setEntity(new StringEntity(json.toString()));
httpPost.setEntity(new StringEntity(jsonstr));
//3.使用httpClient发起请求并响应获取repsonse
return getHttpClientResult(httpResponse,httpClient,httpPost);
/*
httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
//4.解析响应,获取数据
//判断状态码是否是200
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(entity,ENCODING);
}
}
finally {
//5.释放资源
release(httpResponse,httpClient);
}
}
修改如下,在初始化StringEntity时指定UTF-8:
httpPost.setEntity(new StringEntity(jsonstr,"UTF-8"));