您的位置:首页 > 其它

解决服务器收到的post数据出现部分乱码问题

2016-10-29 15:07 555 查看
解决服务器收到的post数据出现部分乱码问题
      今天遇到一个很奇怪的问题,当我使用Java代码进行post提交json数据时,服务器居然出现部分乱码的现象,这些部分乱码不是什么特殊的符号,而是普通的中文,比如:“互联??” 、“网互联网??网” 。我提交json数据时全部是utf-8编码,服务器也是采用utf-8编码,为什么会出现这样的乱码呢?很令人费解!

      于是我就试试通过表单提交会出现这种情况吗,提交后发现服务器打印出的数据是URL编码:%E4%BA%92%E8%81%94%E7%BD%91,既然这样,我把Java代码的post数据也改成了URL编码:URLEncoder.encode(string,"utf-8"),然后服务器端再解码:URLDecoder.decode(str,
"utf-8"),然后打印出的数据就是没有一点乱码的数据了。

      post请求内部采用URL编码!

Java发送post请求

/**
* post请求
* @param url         url地址
* @param jsonParam     参数
* @param noNeedResponse    不需要返回结果
* @return
*/
public static String httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
String strResult = "";
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity;
try {
//对json数据进行URL编码,不然部分文字会出错。
entity = new StringEntity(URLEncoder.encode(jsonParam.toString(),"utf-8"), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
url = URLDecoder.decode(url, "UTF-8");
HttpPost method = new HttpPost(url);
method.setEntity(entity);
HttpResponse result = httpClient.execute(method);
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
/**读取服务器返回过来的数据**/
strResult = EntityUtils.toString(result.getEntity());
Constant.printLog("--Result--:" + strResult);
}
} catch (UnsupportedEncodingException e) {
Constant.printLog("post请求失败:不支持编码异常");
e.printStackTrace();
} catch (ParseException e) {
Constant.printLog("post请求失败:ParseException");
e.printStackTrace();
} catch (IOException e) {
Constant.printLog("post请求失败:IOException");
e.printStackTrace();
}
}
return strResult;
}


服务器接收数据:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String str = FileUtil.readTextFromStream(request.getInputStream(),"utf-8");
System.out.println("服务器接收到数据:"+URLDecoder.decode(str, "utf-8"));
PrintWriter out = response.getWriter();

out.println("数据已收到!");
out.flush();
out.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐