How can I get the cookies from HttpClient?

前端 未结 5 1763
难免孤独
难免孤独 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:34

    As Matt Broekhuis answered in a comment on this answer above, you can use DefaultHttpClient.getCookieStore()

    Note, that at the time that I answered my server was limited to httpclient-4.2.5. DefaultHttpClient is now deprecated as of 4.3. I'm going to leave this answer here because others might find themselves in the same situation and the original poster specified they were using 4.1.2.

    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.cookie.Cookie;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    import java.io.IOException;
    import java.util.List;
    
    public class So8733758 {
    
      public static void main(String... args) throws IOException {
        final HttpUriRequest request = new HttpGet("http://stackoverflow.com");
        final DefaultHttpClient http = new DefaultHttpClient();
        http.execute(request);
        final List cookies = http.getCookieStore().getCookies();
        System.out.println(cookies);
      }
    }
    

    which outputs

    [[version: 0][name: __cfduid][value: de2dfa8314f565701cf7b3895206f04d81457380383][domain: .stackoverflow.com][path: /][expiry: Tue Mar 07 11:53:03 PST 2017], [version: 0][name: prov][value: eeee9738-c50b-44f6-a8aa-b54966db1a88][domain: .stackoverflow.com][path: /][expiry: Thu Dec 31 16:00:00 PST 2054]]
    

提交回复
热议问题