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

后端 未结 3 1224
别跟我提以往
别跟我提以往 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<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
            httpHeaders.stream().forEach(System.out::println);
    
            // close client and response
        }
    }
    
    0 讨论(0)
  • 2020-12-14 02:16

    You can use HttpPost, there are methods to add Header to the Request.

    DefaultHttpClient httpclient = new DefaultHttpClient();
    String url = "http://localhost";
    HttpPost httpPost = new HttpPost(url);
    
    httpPost.addHeader("header-name" , "header-value");
    
    HttpResponse response = httpclient.execute(httpPost);
    
    0 讨论(0)
  • 2020-12-14 02:25

    On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

    You have something like this:

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost("www.google.com").setPath("/search")
        .setParameter("q", "httpclient")
        .setParameter("btnG", "Google Search")
        .setParameter("aq", "f")
        .setParameter("oq", "");
    URI uri = builder.build();
    HttpGet httpget = new HttpGet(uri);
    System.out.println(httpget.getURI());
    
    0 讨论(0)
提交回复
热议问题