HttpURLConnection发送中文乱码问题解决
/** * 发送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写入流,