Http传输JSON复习解决乱码问题

我用的是springMvc,最近使用的时候总是发现乱码问题,所有下面代码中加如编码方式,根据自己编码方式修改即可

我做的测试是客户端传递一个json样式的字符串,服务端原样返回

服务端接口:

@RequestMapping("/httpJson")
@ResponseBody //返回字符串
public HttpEntity httpJson(HttpServletRequest request) throws IOException {
   StringBuffer str = new StringBuffer();
   try {
      BufferedReader in =new BufferedReader(
            new InputStreamReader(
                  new BufferedInputStream(request.getInputStream()),"GBK")
      );
      int i;
      char c;
      while ((i=in.read())!=-1) {
         c=(char)i;
         str.append(c);
      }
      System.out.println(str);
   }catch (Exception ex) {
      ex.printStackTrace();
   }
   JSONObject obj= JSONObject.fromObject(str.toString());
   System.out.println(obj.get("name"));
   HttpHeaders headers = new HttpHeaders();
   MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8"));
   headers.setContentType(mediaType);
   return new ResponseEntity<String>(obj.toString(),headers, HttpStatus.OK);
}

客户端实现:

public class Client {
    public static void HttpClientMes() throws IOException {
            HttpClient httpclient = new DefaultHttpClient();
            String uri = "http://localhost:8080/wangdkMvc/httpJson.aido";
            HttpPost httppost = new HttpPost(uri);
            //添加http头信息
            httppost.addHeader("Authorization", "token"); //认证token
            httppost.addHeader("Content-Type", "application/json");
            httppost.addHeader("User-Agent", "imgfornote");

            JSONObject obj = new JSONObject();
            obj.put("name", "中文乱码");
            httppost.setEntity(new StringEntity(obj.toString(),"GBK"));
            HttpResponse response;
            response = httpclient.execute(httppost);
            //返回状态
              int code = response.getStatusLine().getStatusCode();
            System.out.println("返回状态"+code);
            if (code == 200) {
                String mes = new String(EntityUtils.toString(response.getEntity(), "GBK"));//返回json格式
                  System.out.println("mes"+mes);

                if("".equals(mes) || mes==null || mes.length()==0){
                    System.out.println("未取到返回结果");
                }else{
                    obj= JSONObject.fromObject(mes);
                }
            }
    }
    public static void main(String[] args) throws IOException {
        HttpClientMes();
    }
}

客户端控制台结果:


服务端控制台结果:
{"name":"中文乱码"}
中文乱码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值