java httpclient 获取重定向地址
时间: 2024-02-02 12:48:21 浏览: 93
要获取重定向地址,可以使用Apache HttpClient的RedirectStrategy类。以下是一个示例代码:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com");
RequestConfig requestConfig = RequestConfig.custom()
.setRedirectsEnabled(false)
.build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
Header locationHeader = response.getFirstHeader("Location");
if (locationHeader != null) {
String location = locationHeader.getValue();
System.out.println("Redirect location: " + location);
} else {
System.out.println("Location header not found");
}
} else {
System.out.println("Unexpected status code: " + statusCode);
}
} finally {
response.close();
}
```
在这个例子中,我们首先创建了一个HttpClient实例和一个HttpGet请求对象。然后,我们设置请求配置,禁用自动重定向。接下来,我们执行请求并检查响应状态码,如果是重定向状态码(301或302),我们获取Location头并输出重定向地址。否则,我们输出意外的状态码。最后,我们关闭响应对象。
阅读全文