温馨提示×

java重定向设置header的方法是什么

小亿
343
2023-08-07 09:11:49
栏目: 编程语言

在Java中,可以使用HttpURLConnection类来设置HTTP请求的header。具体的方法是通过调用URLConnection的setRequestProperty方法来设置header。

以下是一个示例代码:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置header
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 发送请求并获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
}
}

在上面的示例中,使用setRequestProperty方法来设置User-Agent和Accept-Language两个header。可以根据需要设置其他的header。最后,调用getResponseCode方法来发送请求并获取响应的HTTP状态码。

0