zl程序教程

您现在的位置是:首页 >  Java

当前栏目

httpclient post请求中文乱码解决

2023-02-18 16:29:47 时间

概要:

在使用httpclient发送post请求的时候,接收端中文乱码问题解决。

正文:

我们都知道,一般情况下使用post请求是不会出现中文乱码的。可是在使用httpclient发送post请求报文含中文的时候在发送端数据正常但是到了服务器端就中文乱码了。

解决办法:

发送端进行设置编码如下:

主要代码:

if (null != jsonParam) {

//解决中文问题。

method.addHeader("Content-type","application/json; charset=utf-8");

method.setHeader("Accept", "application/json");

method.setEntity(new StringEntity(jsonParam.toString(), Charset.forName("UTF-8")));

}

HttpResponse result = httpClient.execute(method);

在接收(服务器)端:

主要代码:

@RequestMapping(value = "getJson")

@ResponseBody

public Map getJson(@RequestBody String requestBody, HttpServletRequest request){

requestBody = new String(requestBody.getBytes(), Charset.forName("utf-8"));

JSONObject jsonObject = JSONObject.parseObject(requestBody);

ResultJsonInfo info = JSONObject.parseObject(jsonObject.toJSONString(), ResultJsonInfo.class);

//TODO 处理自己业务

JSONObject result= new JSONObject();

result.put("success", "true");

Map resultMap = new HashMap();

resultMap.put("isok", true);

return resultMap;

}

这样处理之后。再次请求。乱码问题解决。