HttpConnection的post请求发送数据,接收方出现乱码

今天与别人联调接口,对方要求用流来发送数据,于是我这边用Httpconnection的方式发送数据,demo如下


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class TaobaoCourierRegisterTest {


public static void main(String[] args) throws Exception {
String data = "{\"is_success\": true,\"courier_mobile\": \"13888888888\",\"account_id\": \"12345126\",\"status_message\": \"缺少电话\",\"employee_no\": \"123456\",\"delivery_cp_user_id\": \"123456\",\"courier_name\": \"张三\"}";
String result = doPost("http://***.***.***.***:****/bdm/intf/courier_sync/registure.do", data);
System.out.println(result);
}

public static String doPost(String path, String content) throws Exception {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 这里是关键,表示我们要向链接里输出内容
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setConnectTimeout(30*1000);
conn.setReadTimeout(30*1000);
conn.setInstanceFollowRedirects(true);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;utf-8");
conn.connect();
// 获得连接输出流
DataOutputStream out = new DataOutputStream(conn.getOutputStream());


// 把数据写入
out.writeBytes(content);
out.flush();
out.close();


BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
return sb.toString();
} catch (Throwable e) {
throw new Exception("调用远程接口异常!", e);
}
}
}



发送数据后,对方接收的数据显示乱码,然后查找原因,在     http://blog.csdn.net/ananyangyang/article/details/8036800    中找到原因。


修改代码,将out.writeBytes(content);  改成 out.write(content.getBytes());,在进行测试,未接收到乱码。









你可能感兴趣的:(HttpConnection的post请求发送数据,接收方出现乱码)