How can I get the cookies from HttpClient?

前端 未结 5 1749
难免孤独
难免孤独 2020-12-14 06:08

I am using HttpClient 4.1.2

HttpGet httpget = new HttpGet(uri); 
HttpResponse response = httpClient.execute(httpget);

So, how can I get the

5条回答
  •  囚心锁ツ
    2020-12-14 06:12

    Not sure why the accepted answer describes a method getCookieStore() that does not exist. That is incorrect.

    You must create a cookie store beforehand, then build the client using that cookie store. Then you can later refer to this cookie store to get a list of cookies.

    /* init client */
    HttpClient http = null;
    CookieStore httpCookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
    http = builder.build();
    
    /* do stuff */
    HttpGet httpRequest = new HttpGet("http://stackoverflow.com/");
    HttpResponse httpResponse = null;
    try {httpResponse = http.execute(httpRequest);} catch (Throwable error) {throw new RuntimeException(error);}
    
    /* check cookies */
    httpCookieStore.getCookies();
    

提交回复
热议问题