此前部署的某SpringBoot的Restful风格服务接口,某个客户端进行请求时出现了中文乱码的问题。
SpringBoot服务端代码类似如下:
一开始采用了contentType="application/json;charset=utf-8"的解决方法:
//将xml转为json JSONObject xmlToJson = XML.toJSONObject(readXmlContent.toString()); //设置缩进 String jsonString = xmlToJson.toString(4); //输出格式化后的json logger.info(jsonString); String contentType = "application/json;charset=UTF-8"; String result = HttpClientUtil.sendPostRequest(jsonString, pmUrl, contentType);
其中HttpClientUtil.sendPostRequest的方法如下
/** * 向目标url发送Post请求 * * @param jsonString 请求体Json字符串 * @param targetUrl 目标URL * @param contentType contentType * @return */ public static String sendPostRequest(String jsonString, String targetUrl, String contentType) { StringBuilder result = new StringBuilder(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(targetUrl); StringEntity input = new StringEntity(jsonString); input.setContentType(contentType); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 200) { result.append("HTTP Failed, error code : ").append(response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()))); String output; logger.info("receive result from Server:{} \n", targetUrl); while ((output = br.readLine()) != null) { result.append(output).append("\n"); logger.info(output); } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result.toString(); }}
然后......继续中文乱码,被打脸了。左思右想总觉得哪里不对,代码逐行看过去,终于发现。。。
没错,就是这个,将请求体封装成StringEntity的时候,要指定编码
so,关键点根本不在ContentType上, 想当然的解决方案未必能解决实际问题。
即使问题很小知识很基础,但是见小知大,仍然值得吸取教训。