使用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();
}
}
}
就一定会返回图片吗?