Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

java - How can I get the cookies from HttpClient?

I am using HttpClient 4.1.2

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

So, how can I get the cookie values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...