HttpClient4.5 设置 Cookie

操作方法就是使用 CookieStore , 如果服务器返回了cookie ,后面的请求会自动带上这个Cookie

        String url = "http://localhost:8080/list";
        
//        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
//        CloseableHttpClient httpClient = HttpClients.custom()
//                .setDefaultRequestConfig(requestConfig)
//                        .setDefaultCookieStore(cookieStore).build();
         // 重点就是如下这两句代码
        CookieStore cookieStore = new BasicCookieStore();
        Executor executor = Executor.newInstance().use(cookieStore);

        List paramList = Form.form()
                .add("query_hz", "q")
               .build();
        // 编码成GBK
        UrlEncodedFormEntity gbk = new UrlEncodedFormEntity(paramList, "gbk");
        Request post = Request.Post(url)
                .body(gbk) ;

        HttpResponse response = executor.execute(post).returnResponse();

        // 如果服务器有返回cookie,这里可以取到
        List cookies = cookieStore.getCookies();
        // do something

参考:

  • 关于HttpClient自动保存Cookie
  • Apache HttpComponents学习笔记(二):HttpClient 接口
  • Httpclient核心架构设计
  • HttpClient获取Cookie的一次踩坑实录

你可能感兴趣的:(HttpClient4.5 设置 Cookie)