使用HttpURLConnection来获取状态码

在这里设置了setConnectTimeout和setReadTimeout。但好像没起作用,有了解的可以共享一下。

public static void main(String[] args) {
        // start
        try {
            HttpURLConnection httpUrlConn = (HttpURLConnection) new URL(
                    "http://www.baidu.com").openConnection();
            // 设置连接主机超时(单位:毫秒)
            httpUrlConn.setConnectTimeout(200);
            // 设置从主机读取数据超时(单位:毫秒)
            httpUrlConn.setReadTimeout(200);
            System.out.println(new Date());
            int statusCode = httpUrlConn.getResponseCode();
            System.out.println(new Date());
            System.out.println(statusCode);
            if (statusCode != 200) {
                System.out.println("不存在");
            } else {
                System.out.println("可以访问");
            }
            // 打开流关闭
            InputStream is2 = httpUrlConn.getInputStream();
            is2.close();
        } catch (Exception e) {
            System.out.println("error:" + new Date());
            // TODO: handle exception
            System.err.println(e.getMessage());
        }
        // end
    }
使用 `HttpURLConnection` 获取 API 的响应,可以按照以下步骤进行操作: 1. 创建 `URL` 对象,指定要请求的 API 的 URL: ```java URL url = new URL("https://api.example.com/endpoint"); ``` 2. 打开连接并设置请求方法为 GET(或其他适当的方法): ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); ``` 3. 如果需要设置请求头,可以使用 `setRequestProperty` 方法添加请求头参数: ```java connection.setRequestProperty("Content-Type", "application/json"); ``` 4. 发送请求,并获取响应状态码: ```java int responseCode = connection.getResponseCode(); ``` 5. 根据响应状态码判断请求是否成功: ```java if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,读取响应内容 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应内容 System.out.println(response.toString()); } else { // 请求失败,根据需要处理错误 System.out.println("请求失败,错误码:" + responseCode); } ``` 6. 最后,记得关闭连接: ```java connection.disconnect(); ``` 以上是使用 `HttpURLConnection` 获取 API 响应的基本步骤。你可以根据需要调整和扩展代码来适应不同的场景和要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值