HttpClient获取cookie

// 旧版
HttpClient httpClient = new DefaultHttpClient();
// execute get/post/put or whatever
httpClient.doGetPostPutOrWhatever();
// get cookieStore
CookieStore cookieStore = httpClient.getCookieStore();
// get Cookies
List<Cookie> cookies = cookieStore.getCookies();
// 新版
/* init client */
HttpClient http = null;
CookieStore httpCookieStore = new BasicCookieStore();
http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).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();
// 我的
public class MyCookiesForGet {
    private String url;
    private ResourceBundle bundle;
    @BeforeTest
    public void beforeTest(){

        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url")+bundle.getString("getCookie.uri");
    }
    @Test
    public void test1() throws IOException {
        String result;
        BasicCookieStore cookieStore = new BasicCookieStore();
        HttpGet get = new HttpGet(this.url);
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);

        // 获取cookies信息
        List<Cookie> cookies = cookieStore.getCookies();
        for(Cookie cookie:cookies){
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookies key ="+name+",cookies value ="+value);
        }

    }
}

 

posted @ 2021-12-08 21:51  神奇女侠H  阅读(585)  评论(0)    收藏  举报