在 Java 中处理 HTTP 重定向,主要取决于你使用的是哪种 HTTP 客户端。下面按常见方式分别说明。
HttpURLConnection(JDK 原生)HttpURLConnection 默认会自动跟随重定向(仅限 GET/HEAD)。
URL url = new URL("http://example.com/redirect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true); // 默认就是 true
int code = conn.getResponseCode();
如果你想自己控制:
conn.setInstanceFollowRedirects(false);
int code = conn.getResponseCode();
if (code == HttpURLConnection.HTTP_MOVED_PERM
|| code == HttpURLConnection.HTTP_MOVED_TEMP
|| code == 307 || code == 308) {
String location = conn.getHeaderField("Location");
URL newUrl = new URL(location);
HttpURLConnection newConn = (HttpURLConnection) newUrl.openConnection();
}
⚠️ 注意:
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("http://example.com");
CloseableHttpResponse response = client.execute(get);
RequestConfig config = RequestConfig.custom()
.setRedirectsEnabled(false)
.build();
HttpGet get = new HttpGet("http://example.com");
get.setConfig(config);
CloseableHttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() >= 300
&& response.getStatusLine().getStatusCode() < 400) {
Header location = response.getFirstHeader("Location");
}
HttpClient(现代方式 ✅)HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL) // 或 ALWAYS / NEVER
.build();
NORMAL:安全重定向(GET/HEAD)ALWAYS:包括 POSTNEVER:手动处理.followRedirects(HttpClient.Redirect.NEVER)
然后从响应拿 Location:
if (response.statusCode() == 302) {
String location = response.headers().firstValue("Location").get();
}
RestTemplate restTemplate = new RestTemplate();
// 默认会跟随重定向
ResponseEntity<String> response =
restTemplate.getForEntity("http://example.com", String.class);
| 问题 | 说明 |
|---|---|
| POST 重定向 | 默认可能变 GET |
| 相对路径 Location | 需拼完整 URL |
| HTTPS → HTTP | 某些客户端会拒绝 |
| Cookie 丢失 | 重定向后需手动带 |
如果你能告诉我:
我可以给你更精确的代码示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。