java https get请求头设置
时间: 2024-01-02 17:21:31 浏览: 67
JAVA获取HTTP请求头的方法示例
以下是Java中使用HttpsURLConnection发送GET请求并设置请求头的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
public class HttpsGetRequest {
public static void main(String[] args) {
try {
String url = "https://example.com";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// 设置请求头
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.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();
}
}
}
```
阅读全文