从Java HttpClient获取重定向URL的方法如下:
HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300 && response.statusCode() < 400) {
String redirectUrl = response.headers().firstValue("Location").orElse("");
System.out.println("重定向URL: " + redirectUrl);
}
完整的代码示例:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300 && response.statusCode() < 400) {
String redirectUrl = response.headers().firstValue("Location").orElse("");
System.out.println("重定向URL: " + redirectUrl);
}
}
}
这段代码使用Java 11中引入的新的HttpClient API来发送HTTP请求,并通过检查响应的状态码和获取响应头中的Location字段来获取重定向的URL。
领取专属 10元无门槛券
手把手带您无忧上云