[ツール] Java が http リダイレクトでアドレスを要求し、自動的にリダイレクトします
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPGETWithMultipleHeaders {
public static void main(String[] args) {
try {
String urlToRead = "http://example.com"; // 你要请求的URL
while (urlToRead != null) {
URL url = new URL(urlToRead);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 使用GET请求方式
// 设置多个自定义请求头
connection.setRequestProperty("User-Agent", "YourUserAgent");
connection.setRequestProperty("Authorization", "Bearer YourAccessToken");
connection.setRequestProperty("Custom-Header", "CustomValue");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 请求成功,读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
break; // 响应成功,不再重定向
} else if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
// 处理重定向
String newUrl = connection.getHeaderField("Location");
if (newUrl != null) {
urlToRead = newUrl;
} else {
System.out.println("重定向地址未找到。");
break;
}
} else {
System.out.println("HTTP请求失败,响应代码: " + responseCode);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}