如何自定义java requests的请求头

avatar
作者
猴君
阅读量:0

要自定义Java requests的请求头,可以使用URLConnection或HttpClient来发送HTTP请求,并设置请求头。以下是使用URLConnection和HttpClient分别自定义请求头的示例代码:

  1. 使用URLConnection自定义请求头:
import java.net.HttpURLConnection; import java.net.URL;  public class CustomRequestHeader {     public static void main(String[] args) {         try {             URL url = new URL("https://api.example.com");             HttpURLConnection conn = (HttpURLConnection) url.openConnection();                          // 设置请求头             conn.setRequestProperty("Authorization", "Bearer token");             conn.setRequestProperty("Content-Type", "application/json");                          // 发送请求             conn.setRequestMethod("GET");             int responseCode = conn.getResponseCode();                          System.out.println("Response Code: " + responseCode);         } catch (Exception e) {             e.printStackTrace();         }     } } 
  1. 使用HttpClient自定义请求头:
import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder;  public class CustomRequestHeader {     public static void main(String[] args) {         try {             HttpClient httpClient = HttpClientBuilder.create().build();             HttpGet httpGet = new HttpGet("https://api.example.com");                          // 设置请求头             httpGet.addHeader("Authorization", "Bearer token");             httpGet.addHeader("Content-Type", "application/json");                          // 发送请求             HttpResponse response = httpClient.execute(httpGet);                          System.out.println("Response Code: " + response.getStatusLine().getStatusCode());         } catch (Exception e) {             e.printStackTrace();         }     } } 

以上代码示例分别使用URLConnection和HttpClient发送HTTP请求,并设置了Authorization和Content-Type两个自定义请求头。你可以根据需要自定义更多的请求头参数。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!