此前部署的某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上, 想當然的解決方案未必能解決實際問題。
即使問題很小知識很基礎,但是見小知大,仍然值得吸取教訓。