本地测试时返回值:
云服务器上的返回:
同一套代码 云服务器上是war
//获取公众号文章列表
public String getContentList(String token,String offset) throws IOException {
String path = " https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token;
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);//允许写出
connection.setRequestProperty("content-type", "application/json;charset=utf-8");
connection.connect();
// post发送的参数
Map map = new HashMap<>();
map.put("type", "news"); // news表示图文类型的素材,具体看API文档
map.put("offset", Integer.parseInt(offset));
map.put("count", 5);
// 将map转换成json字符串
String paramBody = JSON.toJSONString(map); // 这里用了Alibaba的fastjson
OutputStream out = connection.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(paramBody); // 向流中写入参数字符串
bw.flush();
InputStream in = connection.getInputStream();
byte[] b = new byte[100];
int len = -1;
StringBuffer sb = new StringBuffer();
while ((len = in.read(b)) != -1) {
sb.append(new String(b, 0, len));
}
System.out.println(sb.toString());
in.close();
return sb.toString();
}
解决了!
是因为IO流读写不一致,idea自带UTF-8读写,tomcat没有,所以要在
sb.append(new String(b, 0, len));
加一个编码格式,变成:
sb.append(new String(b, 0, len,"utf-8"));
在读取流的时候就将流给转为"utf-8"
后续读取的话就是正常的中文了
BufferedReader br = new BufferedReader(
new InputStreamReader(in,"UTF-8")); //读取流时就编码