收藏
回答

使用Java调用https://api.weixin.qq.com/wxa/getwxacodeun

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug https://api.weixin.qq.com/wxa/getwxacodeun 工具 6.5.5 2.0.0

使用Java 调用https://api.weixin.qq.com/wxa/getwxacodeun 获取微信二维码时,生成的二维码图片破损如何解决?

public static void generateQrcode(String scene, String page, String filePath) {
    HttpURLConnection connection = null;
    try {
        String accessToken = getAccessToken();
        URL url = new URL(WXACODE_URL+"?access_token=" + accessToken);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        JSONObject requestBody = new JSONObject();
        requestBody.put("scene", scene);
        requestBody.put("page", page);
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.toString().getBytes("utf-8");
            os.write(input, 0, input.length);
        }
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应流
            try (InputStream is = connection.getInputStream();
                 FileOutputStream fos = new FileOutputStream(filePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                System.out.println("二维码生成成功,保存路径:" + filePath);
            }
        } else {
            System.out.println("请求失败,响应状态码:" + responseCode);
        }
    } catch (IOException e) {
        System.err.println("发生 IO 异常: " + e.getMessage());
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}


回答关注问题邀请回答
收藏

1 个回答

  • Mr.Zhao
    Mr.Zhao
    04-08

    就一定会返回图片吗?

    04-08
    有用
    回复 3
    • setup
      setup
      04-08
      返回图片了,图片破损
      04-08
      回复
    • Mr.Zhao
      Mr.Zhao
      04-08回复setup
      你怎么知道返回的是图片?
      04-08
      回复
    • Mr.Zhao
      Mr.Zhao
      04-08回复setup
      你代码里面就没看到判断是否是图片啊,怎么确定一定返回图片
      04-08
      回复
登录 后发表内容