/** * 發送http POST請求 * * @param * @return 遠程響應結果 */ public static String sendPost(String u, String json) throws Exception { StringBuffer sbf = new StringBuffer(); try { URL url = new URL(u); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (!"".equals(json)) { //out.writeBytes(json); out.write(json.getBytes()); } out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sbf.append(lines); } System.out.println(sbf); reader.close(); // 斷開連接 connection.disconnect(); } catch (IOException e) { e.printStackTrace(); throw e; } return sbf.toString(); }
重點在於:替換out.writeBytes(json);為 out.write(json.getBytes());
原因為:out.writeBytes(json);該語句在轉中文時候,已經變成亂碼
public final void writeBytes(String s) throws IOException { int len = s.length(); for (int i = 0 ; i < len ; i++) { out.write((byte)s.charAt(i)); } incCount(len); }
因為java里的char類型是16位的,一個char可以存儲一個中文字符,在將其轉換為 byte后高8位會丟失,這樣就無法將中文字符完整的輸出到輸出流中。所以在可能有中文字符輸出的地方最好先將其轉換為字節數組,然后再通過write寫入流,