Bagaimana saya bisa mendapatkan cookie dari HttpClient?

Saya menggunakan HttpClient 4.1.2

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

Jadi, bagaimana saya bisa mendapatkan nilai cookie?

Tidak yakin mengapa jawaban yang diterima menjelaskan metode getCookieStore() yang tidak ada. Itu tidak benar.

Anda harus membuat sebuah cookie store terlebih dahulu, kemudian membangun klien menggunakan cookie store tersebut. Kemudian Anda dapat merujuk ke cookie store ini untuk mendapatkan daftar cookie.

/* 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();
Komentar (4)

Namun satu lagi untuk membuat orang lain memulai, melihat metode yang tidak ada menggaruk-garuk kepala mereka ...

import org.apache.http.Header;
import org.apache.http.HttpResponse;

Header[] headers = httpResponse.getHeaders("Set-Cookie");
for (Header h : headers) {
    System.out.println(h.getValue().toString());  
}

Ini akan mencetak nilai-nilai cookie. Respon server dapat memiliki beberapa field header Set-Cookie, jadi Anda perlu mengambil array dari Headers

Komentar (0)
Larutan

Harap Dicatat: Tautan pertama menunjuk ke sesuatu yang dulu bekerja di HttpClient V3. Temukan info terkait V4 di bawah ini.

Ini seharusnya menjawab pertanyaan Anda

http://www.java2s.com/Code/Java/Apache-Common/GetCookievalueandsetcookievalue.htm

Berikut ini relevan untuk V4:

...sebagai tambahan, javadocs harus berisi lebih banyak informasi tentang penanganan cookie

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html

dan berikut ini adalah tutorial untuk httpclient v4:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

Dan berikut ini adalah beberapa pseudo-code yang membantu (saya harap, ini hanya berdasarkan dokumen):

HttpClient httpClient = new DefaultHttpClient();
// execute get/post/put or whatever
httpClient.doGetPostPutOrWhatever();
// get cookieStore
CookieStore cookieStore = httpClient.getCookieStore();
// get Cookies
List cookies = cookieStore.getCookies();
// process...

Pastikan Anda membaca javadocs untuk ResponseProcessCookies dan AbstractHttpClient.

Komentar (10)