如題,HttpURLConnection使用POST方法發起http請求,參數通過form來傳遞(並非使用URL傳遞參數),出現了中文亂碼的情況。
具體描述為:將請求參數以
Content-Disposition: form-data; name="name" value
形式上傳,然后使用OutputStream.write傳送,結果中文參數會出現亂碼。
因為調用的方法是另外的人開發的系統,他們設定了通過UTF-8解碼讀取,所以要求調用時使用UTF-8進行編碼后才可進行。
百度谷歌了一下解決方法,有教charset設置UTF8的,如
HttpURLConnection conn = null; conn.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8; ");
也有很復雜的,每次參數拼接都設定編碼的,如
// 首先組拼文本類型的參數 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); }
但是,這些方法都試用遍了,還是沒有起效。
后來我通過這樣,解決了問題:
StringBuffer strBuf = new StringBuffer();
strBuf.append("Content-Disposition: form-data; name=\""
+ name+ "\"\r\n\r\n");
strBuf.append(value);
out.write(strBuf.toString().getBytes("UTF-8"));
代碼不是完整的。不過做法是很簡單的。只需保持原本StringBuffer將參數的key和value拼接在Content-Disposition: form-data; name=的過程,最后,out.write一個byte[]時,保證這個參數byte[]數組是UTF-8編碼。原來的String.getBytes()換成String.getBytes("UTF-8")即可!
有類似疑難的情況,可以這樣解決!