我用的是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":"中文乱码"}
中文乱码
中文乱码