Java HttpURLConnection遵循重定向示例
时间: 2024-02-22 15:48:05
浏览: 38
以下是使用Java HttpURLConnection遵循重定向的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) throws IOException {
String url = "https://www.example.com";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setInstanceFollowRedirects(false); // 禁用自动重定向
// 发送GET请求
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
// 获取重定向URL
String redirectUrl = conn.getHeaderField("Location");
// 手动发送重定向请求
URL newUrl = new URL(redirectUrl);
conn = (HttpURLConnection) newUrl.openConnection();
conn.setRequestMethod("GET");
responseCode = conn.getResponseCode();
// 处理响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
in.close();
System.out.println(response.toString());
在该示例中,我们首先发送一个GET请求,并检查响应代码是否为重定向代码(HTTP_MOVED_TEMP或HTTP_MOVED_PERM)。如果是,我们手动获取重定向URL并发送另一个GET请求。最后,我们处理响应并将其输出到控制台。注意,我们在第一个连接对象上禁用了自动重定向,以便我们可以手动处理重定向。