使用java.net.*发送API请求无法获取400+响应体的解决办法咨询
解决办法
问题根源在于HttpURLConnection在收到400及以上的错误状态码时,调用getInputStream()会直接抛出IOException,此时错误响应体需要通过getErrorStream()方法获取。
你需要调整代码逻辑,先获取响应状态码,根据状态码选择读取输入流或错误流,同时在异常捕获中也处理错误流的读取:
修改后的代码
public static String sendPostRequest(String requestUrl, String payload, Map<String, String> requestProperties) { StringBuffer jsonString = new StringBuffer(); HttpURLConnection connection = null; BufferedReader br = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); for (Map.Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); writer.write(payload); writer.close(); // 获取响应状态码 int responseCode = connection.getResponseCode(); // 根据状态码选择对应的流 InputStream inputStream; if (responseCode >= HttpURLConnection.HTTP_BAD_REQUEST) { inputStream = connection.getErrorStream(); } else { inputStream = connection.getInputStream(); } br = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = br.readLine()) != null) { jsonString.append(line); } } catch (Exception e) { log.error("Error for call " + requestUrl); log.error(e.getMessage()); // 异常情况下尝试读取错误流 if (connection != null) { try (BufferedReader errorBr = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { String line; while ((line = errorBr.readLine()) != null) { jsonString.append(line); } } catch (Exception ex) { log.error("Failed to read error stream", ex); } } } finally { // 确保资源关闭 try { if (br != null) br.close(); if (connection != null) connection.disconnect(); } catch (Exception e) { log.error("Failed to close resources", e); } } return jsonString.toString(); }
关键调整点
- 先调用
getResponseCode()获取响应状态码,这一步会触发请求的实际发送,避免直接调用getInputStream()抛出异常 - 根据状态码判断使用
getInputStream()还是getErrorStream() - 在finally块中统一关闭流和连接,避免资源泄漏
- 异常捕获中额外处理错误流读取,确保即使抛出异常也能拿到错误响应体
内容的提问来源于stack exchange,提问作者Harish Algat
相关产品推荐
相关产品推荐

