java创建get请求并设置请求头
时间: 2023-05-20 07:01:21 浏览: 57
可以使用 Java 的 HttpURLConnection 类来创建 GET 请求并设置请求头。以下是示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("Response code: " + responseCode);
}
}
```
在上面的代码中,我们首先创建一个 URL 对象,然后使用它来打开一个 HttpURLConnection 连接。我们设置请求方法为 GET,并设置 User-Agent 请求头。最后,我们发送请求并获取响应码。
相关问题
java https get请求头设置
以下是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();
}
}
}
```
java发送get请求并设置header
可以使用 Java 中的 HttpURLConnection 类来发送 GET 请求并设置 Header。
以下是一个简单的示例:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetRequestWithHeader {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/data"; //待请求的 URL
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//设置请求方法为 GET
con.setRequestMethod("GET");
//设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//获取响应状态码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
//读取响应内容
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());
}
}
```
在上述示例中,我们在发送 GET 请求之前,使用 `setRequestProperty` 方法设置了请求头信息。你可以根据需要设置不同的请求头信息。