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

    作者:以罗伊
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    C#中调用DTS
    经典问题:向setTimeout传递函数参数
    C#.NET 中的类型转换
    SQL语句导入导出大全 (转载)
    js脚本defer的作用
    [转]使用 Java API 处理 WebSphere MQ 大消息
    WideCharToMultiByte 宽字节转换为多字节
    [原].NET数据库开发中请注意区域时间格式
    输出页眉和页脚的简单HTTP模块实践
    浅析ASP.NET HTTP Module
  • 原文地址:https://www.cnblogs.com/my-ordinary/p/11963671.html
Copyright © 2020-2023  润新知