HttpPost发送JSON数据中文乱码问题。

Android移动终端通过 HttpPost发送JSON数据时出现中文乱码问题的解决方案。通常都用UTF-8 编码。

1、客户端 postData为JSON数据JSONObject.
注意点:发送和接收时转码。
public static String httpPostData(String uri, int requestTimeOut, String postData) {
String retStr = "failure";
int tmout = 5;
if (requestTimeOut > 0){
tmout = requestTimeOut;
}
try {
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("charset", "UTF-8");
    HttpConnectionParams.setConnectionTimeout(httpParams,tmout * 1000);  //毫秒
    HttpConnectionParams.setSoTimeout(httpParams, tmout * 1000);    
HttpClient httpClient = new DefaultHttpClient(httpParams);

HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(postData.toString(),"UTF-8"));
HttpResponse response;
response = httpClient.execute(httpPost);
//检验状态码,如果成功接收数据
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
retStr = EntityUtils.toString(response.getEntity(),"UTF-8");
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
}
System.out.println("httpPostData() return:" + retStr);
return retStr;
}



2、WEB SERVLET
我用的是Spring3.1框架
注意点:BufferedReader取数时一定要转码。环境不同你可以试着转成GBK码试试。
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ServiceException {
    request.setCharacterEncoding("UTF-8"); //避免中文乱码 POST方式提交 
    response.setContentType("text/json;charset=UTF-8");
        String responseData="[{}]"; //JSONArray String
            // 读取请求JSON数据       
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
        String line = "";
        StringBuilder sbf = new StringBuilder();
        while((line = br.readLine())!=null){
            sbf.append(line);
        }
        String postData = sbf.toString();
        if(postData==null || "".equals(postData)){
        postData = "{}"; //JSON数据
         }
        System.out.println("postData:" + postData);
   }

共同学习,共同进步,不对之处还望指正。
### HTTP 发送数据时避免乱码问题的编码设置 为了避免HTTP发送JSON或其他数据时出现乱码问题,可以采取以下措施: #### 1. 统一字符集 确保客户端和服务端都使用相同的字符集。推荐使用UTF-8作为标准字符集,因为它能够支持几乎所有的字符[^1]。 #### 2. 设置Content-Type头信息 在发送HTTP请求时,通过`Content-Type`头部指定编码方式。例如,在发送JSON数据时,应将`Content-Type`设为`application/json;charset=UTF-8`,这表明数据是以UTF-8编码的JSON格式传递的[^3]。 ```python import requests headers = { 'Content-Type': 'application/json;charset=UTF-8' } data = {"key": "中文"} response = requests.post('http://example.com/api', json=data, headers=headers) ``` #### 3. 避免字节截断 在Java中,如果使用`writeBytes()`方法写入字符串,可能会因为丢弃多余的字节而导致乱码。建议改用`OutputStreamWriter`并显式指定编码为UTF-8来避免此类问题[^2]。 ```java OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8); osw.write(jsonString); osw.flush(); ``` #### 4. 处理Spring框架中的乱码 如果是基于Spring框架的应用程序,当返回值为`String`类型时,默认情况下会使用`ISO-8859-1`编码,而不是UTF-8。可以通过修改配置文件或者调整响应体的方式解决此问题。 ##### 方法一:全局配置 在Spring Boot项目中,可以在`application.properties`或`application.yml`中添加如下配置项: ```properties spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true ``` ##### 方法二:局部调整 针对特定接口,手动设置响应体的编码方式: ```java @RequestMapping(value = "/api", produces = "application/json;charset=UTF-8") @ResponseBody public String api() { return "{\"message\": \"中文\"}"; } ``` #### 5. 测试Socket通信中的乱码 对于Socket通信场景下的乱码问题,需确认双方均采用一致的编码方式进行数据交换。通常也需要设定为UTF-8以兼容多语言环境[^4]。 --- ### 总结 综上所述,无论是哪种情况引发的乱码现象,核心原则都是保持整个链路内的编码一致性,并优先选用广泛接受的标准——UTF-8编码方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值