轉自:http://blog.csdn.net/hwj3747/article/details/53635539
在Java使用HttpURLConnection請求rest接口的時候出現了POST請求出現中文亂碼的問題,經過把傳入的String通過多種方法進行編碼發現都解決不了,如下:
String teString=new String("你好".getBytes("ISO-8859-1"),"UTF-8");
網上HttpURLConnection的請求通常是這樣子的:
public static String PostRequest(String URL,String obj) { String jsonString=""; try { //創建連接 URL url = new URL(URL); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); //設置請求方法 connection.setRequestProperty("Charsert", "UTF-8"); //設置請求編碼 connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); //POST請求 DataOutputStream out = new DataOutputStream( connection.getOutputStream()); //關鍵的一步 out.writeBytes(obj); out.flush(); out.close(); // 讀取響應 if (connection.getResponseCode()==200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } jsonString=sb.toString(); reader.close(); }//返回值為200輸出正確的響應信息 if (connection.getResponseCode()==400) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } jsonString=sb.toString(); reader.close(); }//返回值錯誤,輸出錯誤的返回信息 // 斷開連接 connection.disconnect(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonString; }
需要注意的是返回值為200時,connection.getInputStream()才有值,返回值為400時connection.getInputStream()是空的,connection.getErrorStream()才有值。
以上是大多數網上博客文章的寫法,但是我用這種方法遇到了中文亂碼的問題。在out.writeBytes(obj);這一步無論對obj這個字符串怎樣轉換,得到的結果還是亂碼,最終得到的解決方法是這樣的:
把這個部分代碼,
DataOutputStream out = new DataOutputStream( connection.getOutputStream()); //關鍵的一步 out.writeBytes(obj);
改成
PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8")); out.println(obj);
解決。
