温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java HTTP怎么处理重定向

发布时间:2026-10-01 13:36:19 来源:亿速云 阅读:91 作者:小樊 栏目:编程语言

在 Java 中处理 HTTP 重定向,主要取决于你使用的是哪种 HTTP 客户端。下面按常见方式分别说明。


一、使用 HttpURLConnection(JDK 原生)

1️⃣ 默认行为

HttpURLConnection 默认会自动跟随重定向(仅限 GET/HEAD)。

URL url = new URL("http://example.com/redirect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true); // 默认就是 true

int code = conn.getResponseCode();

2️⃣ 手动处理重定向

如果你想自己控制:

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

⚠️ 注意:

  • POST 重定向默认不自动跟随
  • 307 / 308 不会自动把 POST 转 GET

二、使用 Apache HttpClient(推荐)

1️⃣ 自动重定向(默认)

CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("http://example.com");
CloseableHttpResponse response = client.execute(get);

2️⃣ 禁用自动重定向

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");
}

三、使用 Java 11+ HttpClient(现代方式 ✅)

1️⃣ 默认自动重定向

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://example.com"))
        .build();

HttpResponse<String> response =
        client.send(request, HttpResponse.BodyHandlers.ofString());

2️⃣ 自定义重定向策略

HttpClient client = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NORMAL) // 或 ALWAYS / NEVER
        .build();
  • NORMAL:安全重定向(GET/HEAD)
  • ALWAYS:包括 POST
  • NEVER:手动处理

3️⃣ 手动处理重定向

.followRedirects(HttpClient.Redirect.NEVER)

然后从响应拿 Location:

if (response.statusCode() == 302) {
    String location = response.headers().firstValue("Location").get();
}

四、Spring RestTemplate

RestTemplate restTemplate = new RestTemplate();

// 默认会跟随重定向
 ResponseEntity<String> response =
        restTemplate.getForEntity("http://example.com", String.class);

五、常见坑总结

问题 说明
POST 重定向 默认可能变 GET
相对路径 Location 需拼完整 URL
HTTPS → HTTP 某些客户端会拒绝
Cookie 丢失 重定向后需手动带

如果你能告诉我:

  • 用的是哪种客户端(HttpURLConnection / HttpClient / Java11 / Spring)
  • 是 GET 还是 POST
  • 是否需要保留请求体或 Cookie

我可以给你更精确的代码示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手