在发送post请求时,从画面取到的数据是【假名】,在向后台服务端传递过程中,发现数据变成【???】,经调查发现是字符编码问题。
添加下列代码后,数据传递正确。
// 设置参数---设置消息实体 也就是携带的数据
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
// 设置编码格式
entity.setContentEncoding("UTF-8");
/**
* 发送 post 请求
*
* @param url 请求地址
* @param jsonStr Form表单json字符串
* @return 请求结果
*/
public static String post(String url, String jsonStr) {
// 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建post请求方式实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头 发送的是json数据格式
httpPost.setHeader("Content-type", "application/json;charset=utf-8");
httpPost.setHeader("Connection", "Close");
// 设置参数---设置消息实体 也就是携带的数据
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
// 设置编码格式
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
// 把请求消息实体塞进去
httpPost.setEntity(entity);
// 执行http的post请求
CloseableHttpResponse httpResponse;
String result = null;
try {
httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}