是这个请求需要等很久才给响应,想保证response.toString()是获取的响应信息而不是空的

理解了。为了确保 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时才会继续读取响应内容。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值