java如何在http请求时,忽略异常,拿到响应头信息

文章介绍了在Java中使用HttpURLConnection和ApacheHttpClient两种方式来发送HTTP请求并获取响应头信息。对于HttpURLConnection,通过建立连接并调用getHeaderFields()方法可获取头信息;而ApacheHttpClient则提供CloseableHttpClient执行请求,通过getAllHeaders()获取头信息。
摘要由CSDN通过智能技术生成

在 Java 中使用 HttpURLConnection 发送 HTTP 请求时,可以通过以下方式忽略异常并拿到响应头信息。

try {
    URL url = new URL("http://example.com");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);
    connection.setDoInput(true);
    connection.connect();
    Map<String, List<String>> headers = connection.getHeaderFields();
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
} catch (IOException e) {
    // ignore
}

其中,connection.getHeaderFields() 方法返回响应头信息,以键值对形式存储在 Map 对象中。

也可以使用 Apache HttpClient 第三方库来实现这一目的,该库提供了更为丰富的API和高级的功能。

在 HttpClient 中,你可以使用 CloseableHttpClient 对象发送请求并得到响应头信息

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request =new HttpGet("http://example.com");

CloseableHttpResponse response = httpClient.execute(request);
try {
    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println(header.getName() + ": " + header.getValue());
    }
} catch (IOException e) {
    // ignore
} finally {
    response.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值