文章代码参考摘自此处:https://blog.csdn.net/qq_39308071/article/details/115985685
本人主要强调2个点:
1、writeBytes会出现中文问题,因为java里的char类型是16位的,一个char可以存储一个中文字符,在将其转换为 byte后高8位会丢失;所以得用write。
2.在获取bytes时,加UTF-8,例如getBytes(“UTF-8”),解决用了第一点也还是乱码问题
代码示例:
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept","*/*");
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
out.write(date.getBytes("UTF-8"));//date是json格式的字符串
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while((line = in.readLine()) != null){
returnStr += line;
}
} catch (Exception e) {
log.error(" sendPostErr",e);
}finally{
try {
if(out !=null){
out .colse()
}
if(in !=null){
in.colse()
}
} catch (Exception e) {
log.error(" out/in colse error", e);
}
}