理解了。为了确保 response.toString()
能够获取到有效的响应信息,你可以在连接读取响应之前添加一些逻辑来检查是否有可用的响应。你可以使用 connection.getResponseCode()
方法来检查响应状态码,如果状态码是200(表示成功),则可以继续读取响应内容,否则可能需要重试或者处理其他情况。
以下是修改后的代码示例:
private static String sendPostRequest(String apiUrl, String jsonInputString) {
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// 启用输入输出流
connection.setDoOutput(true);
// 写入 JSON 数据
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// 获取响应状态码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取返回的数据
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
}
} else {
// 处理响应错误
System.out.println("Failed to receive response. Response code: " + responseCode);
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
这样,在尝试读取响应之前,会先检查响应状态码,只有当状态码是200时才会继续读取响应内容。