HttpClient获取cookies信息

1.首先配置好测试用的mock接口

[
  {
    "description": "模拟会返回cookies的get请求",
    "request": {
      "uri": "/getcookies",
      "method": "get"
    },
    "response": {
      "cookies": {
        "login": "flase"
      },
      "json": {
        "text": "这是一个会返回cookies信息的get请求"
      }
    }
  },
  {
    "description": "模拟一个带cookies的get请求",
    "request": {
      "uri": "/get/with/cookies",
      "method": "get",
      "cookies": {
        "login": "true",
        "token": "test"
      }
    },
    "response": {
      "json": {
        "text": "这是一个需要携带cookies信息才能访问的get请求"
      }
    }
  }

]

2.在Terminal里执行命令,启动mock

java -jar -Dfile.encoding=UTF-8 ./moco-runner-0.11.0-standalone.jar http -p 8890 -c startupGet.json

3.在httpclient调用方法里获取cookies信息

/**
 * http请求方法的封装
 */
public class RestClient {
      CookieStore store;

    /**
     * 不带请求头的get方法封装
     * @param url
     * @return 返回响应对象
     * @throws ClientProtocolException
     * @throws IOException
     */

    public CloseableHttpResponse get(String url) throws ClientProtocolException, IOException {

        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 设置cookies信息
        store = new BasicCookieStore();
        httpclient = HttpClients.custom().setDefaultCookieStore(store).build();
        //创建一个Httpget的请求对象
        HttpGet httpget = new HttpGet(url);
        //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = httpclient.execute(httpget);

        // 读取cookie信息
        List<Cookie> cookielist = store.getCookies();
        for (Cookie cookie : cookielist) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie:name=" + name + ";value=" + value);
        }
        return httpResponse;

    }
}    

4.在httpclient调用方法里携带cookies访问信息

    /**
     * 不带请求头带cookies信息的get方法封装
     * @param url
     * @param cookieList,存放多个cookies信息
     * @return 返回响应对象
     * @throws ClientProtocolException
     * @throws IOException
     */

    public CloseableHttpResponse get(String url,ArrayList cookieList) throws ClientProtocolException, IOException {

        // 设置cookies信息
        store = new BasicCookieStore();
        for (Object x:
                cookieList) {
            store.addCookie((Cookie) x);
        }
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(store).build();

        //创建一个Httpget的请求对象
        HttpGet httpget = new HttpGet(url);
        //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = httpclient.execute(httpget);

        return httpResponse;

    }

5.调用返回cookies信息的接口和需要携带cookies信息才能访问的接口

public class Case2 {

    public static void main(String[] args){

    @Test
    public void test3() throws IOException {
        String url;
        url = "http://127.0.0.1:8890/getcookies";
        RestClient restClient = new RestClient();

        CloseableHttpResponse closeableHttpResponse = restClient.get(url);
        JSONObject responseJson = restClient.getResponseJson(closeableHttpResponse);
        System.out.println("responseJson:" + responseJson);
    }

    @Test
    public void test4() throws IOException {
        String url;
        url = "http://127.0.0.1:8890/get/with/cookies";
        //添加cookies信息
        BasicClientCookie cookie1 = new BasicClientCookie("login","true");
        cookie1.setVersion(0);
        cookie1.setDomain("127.0.0.1");
        cookie1.setPath("/get/with/cookies");
        //添加cookies信息
        BasicClientCookie cookie2 = new BasicClientCookie("token","test");
        cookie2.setVersion(0);
        cookie2.setDomain("127.0.0.1");
        cookie2.setPath("/get/with/cookies");

        ArrayList cookieList = new ArrayList();
        cookieList.add(cookie1);
        cookieList.add(cookie2);

        RestClient restClient = new RestClient();
        CloseableHttpResponse closeableHttpResponse = restClient.get(url,cookieList);
        JSONObject responseJson = restClient.getResponseJson(closeableHttpResponse);
        System.out.println("responseJson:" + responseJson);
    }

}

执行结果:

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient session是指在使用HttpClient库进行HTTP通信时,为了保持会话状态而使用的机制。有两种常见的方式来实现HttpClient session。一种是将HttpClient实例保存在web应用的session中,每次请求时取出并使用该实例,因为HttpClient会维持cookies。另一种方式是在每次请求时,将上次请求获取cookies带入请求中,无需将HttpClient保存在session中。\[1\] 在HttpClient的3.x版本中,还可以使用HttpClient::enableCookies方法来支持使用cookie实现会话。通过启用cookie,可以方便地实现HttpClient的会话功能。\[2\] 在cocos2d-x游戏开发框架中,可以使用cocos2d::network::HttpClient::getInstance()->enableCookies(NULL)来启用HttpClientcookie功能,从而实现会话管理。\[3\] #### 引用[.reference_title] - *1* [HttpClient简单请求和session的保持](https://blog.csdn.net/wangxianhong/article/details/9104953)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [HttpClient session](https://blog.csdn.net/weixin_43360707/article/details/98482956)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值