How to add,set and get Header in request of HttpClient?

后端 未结 3 1254
别跟我提以往
别跟我提以往 2020-12-14 01:48

In my application I need to set the header in the request and I need to print the header value in the console... So please give an example to do this the HttpClient or edit

3条回答
  •  星月不相逢
    2020-12-14 02:12

    You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

    public class App {
    
        public static void main(String[] args) throws IOException {
    
            CloseableHttpClient client = HttpClients.custom().build();
    
            // (1) Use the new Builder API (from v4.3)
            HttpUriRequest request = RequestBuilder.get()
                    .setUri("https://api.github.com")
                    // (2) Use the included enum
                    .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                    // (3) Or your own
                    .setHeader("Your own very special header", "value")
                    .build();
    
            CloseableHttpResponse response = client.execute(request);
    
            // (4) How to read all headers with Java8
            List
    httpHeaders = Arrays.asList(response.getAllHeaders()); httpHeaders.stream().forEach(System.out::println); // close client and response } }

提交回复
热议问题