收藏
回答

为什么本地获取公众号素材列表没问题,可放到服务器上读取就变成了字符了? 还有标题中有方块问号

本地测试时返回值:

云服务器上的返回:

同一套代码 云服务器上是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();
}
最后一次编辑于  2020-05-18
回答关注问题邀请回答
收藏

1 个回答

  • 少吃零食 多睡觉
    少吃零食 多睡觉
    2020-05-14

    解决了!

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

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

    加一个编码格式,变成:

    sb.append(new String(b, 0, len,"utf-8"));
    
    2020-05-14
    有用 1
    回复 2
    • 少吃零食 多睡觉
      少吃零食 多睡觉
      2020-05-18
      方块问号是因为读取流的时候一个字被多个字节拆开了
      在读取流的时候就将流给转为"utf-8"


      后续读取的话就是正常的中文了
      2020-05-18
      1
      回复
    • 少吃零食 多睡觉
      少吃零食 多睡觉
      2020-05-18回复少吃零食 多睡觉
      666  厉害厉害
      2020-05-18
      1
      回复
登录 后发表内容
问题标签