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

博主遇到在使用Java进行POST提交JSON数据时,服务器接收到的部分中文出现乱码问题。尽管都设置为UTF-8编码,仍出现“互联??”等乱码。通过尝试表单提交并观察URL编码方式,博主将Java代码中的POST数据改为URL编码并服务器端解码,成功解决了乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决服务器收到的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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值