要自定義Java requests的請求頭,可以使用URLConnection或HttpClient來發送HTTP請求,并設置請求頭。以下是使用URLConnection和HttpClient分別自定義請求頭的示例代碼:
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();
}
}
}
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兩個自定義請求頭。你可以根據需要自定義更多的請求頭參數。