码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient怎么获取cookie

时间:2019-11-30 20:44:46      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:trace   cookies   response   exec   color   参考   ror   拼接   url   

// 旧版
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();
// process...
// 新版
/* 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();
// 我的
@Test
    public void testGetCookies1() throws IOException {
        String result;
        // 获取文件 拼接
        String uri = bundle.getString("getCookies.uri");
        String getTestUrl = this.url + uri;

        try {

            BasicCookieStore cookieStore = new BasicCookieStore();

            // 获取 响应
            HttpGet get = new HttpGet(getTestUrl);
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//            CloseableHttpClient build = HttpClientBuilder.create().build();
//            CloseableHttpResponse execute = build.execute(get);
            CloseableHttpResponse execute = httpClient.execute(get);
            result = EntityUtils.toString(execute.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 + "  value= " + value);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

 https://stackoverflow.com/questions/8733758/how-can-i-get-the-cookies-from-httpclient

HttpClient怎么获取cookie

标签:trace   cookies   response   exec   color   参考   ror   拼接   url   

原文地址:https://www.cnblogs.com/my-ordinary/p/11963671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!