为什么本地获取公众号素材列表没问题,可放到服务器上就乱码了?
发布于 5 年前 作者 wenming 15192 次浏览 来自 官方Issues

本地测试时返回值:

云服务器上的返回:

同一套代码 云服务器上是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<String, Object> 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();
}
1 回复

解决了!

是因为IO流读写不一致,idea自带UTF-8读写,tomcat没有,所以要在

sb.append(new String(b, 0, len));

加一个编码格式,变成:

sb.append(new String(b, 0, len,"utf-8"));
回到顶部