Java 如何处理 HTTP 重定向

发布时间:2025-01-19 13:31:22 作者:小樊
来源:亿速云 阅读:96

在 Java 中,处理 HTTP 重定向通常涉及到两个方面:检测和处理重定向以及获取重定向后的 URL

  1. 使用 HttpURLConnection 类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        try {
            String url = "http://example.com/some-redirect-url";
            URL obj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

            // 设置允许重定向
            connection.setInstanceFollowRedirects(true);

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // 获取重定向后的 URL
                String redirectedUrl = connection.getHeaderField("Location");
                System.out.println("Redirected URL: " + redirectedUrl);
            } else {
                // 处理其他响应
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                System.out.println(response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. 使用 Apache HttpClient 库:

首先,您需要将 Apache HttpClient 库添加到项目中。如果您使用 Maven,可以在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

然后,您可以使用以下代码处理 HTTP 重定向:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Main {
    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://example.com/some-redirect-url";

        try {
            // 创建 HttpGet 对象并设置允许重定向
            HttpGet httpGet = new HttpGet(url);
            httpGet.setFollowRedirects(true);

            // 执行请求并获取响应
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == 301 || responseCode == 302) {
                // 获取重定向后的 URL
                String redirectedUrl = httpResponse.getFirstHeader("Location").getValue();
                System.out.println("Redirected URL: " + redirectedUrl);
            } else {
                // 处理其他响应
                HttpEntity httpEntity = httpResponse.getEntity();
                String responseBody = EntityUtils.toString(httpEntity);
                System.out.println(responseBody);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

这两个示例都会检测和处理 HTTP 重定向,并在发生重定向时获取重定向后的 URL。

推荐阅读:
  1. java-web学习笔记(第二章)
  2. java如何实现响应重定向发送post请求

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

java

上一篇:Java 与 HTTP/3 协议的兼容性问题探讨

下一篇:CentOS系统如何安装

相关阅读

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

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