在 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();
}