HttpClient模拟带Cookie的登录请求

转载自AndyWei123的博客

模拟登陆

首先是模拟登录,一般在一些防爬网站需要携带一些基础http头模拟成浏览器登录,一般只需要User-agent使用火狐浏览器,这里就不涉及了,登录通常是把用户名和密码加密发送给后台,当服务器收到HTTP请求时,服务器可以在响应头里面添加一个Set-Cookie选项。浏览器收到响应后通常会保存下Cookie,之后对该服务器每一次请求中都通过Cookie请求头部将Cookie信息发送给服务器。另外,Cookie的过期时间、域、路径、有效期、适用站点都可以根据需要来指定。这时浏览器就会为这个domain创建一个cookie 一般是 key = token ,value = “******”(加密信息,包括用户名和密码还有一些基础信息),后端可以直接通过解析http头来获取改用户和验证。(具体细节可以参考这里)

模拟登录(写cookie)

      CloseableHttpClient httpClient = HttpClients.custom()
          .setConnectionTimeToLive(6000, TimeUnit.MILLISECONDS).build();
      HttpPost httpPost = new HttpPost(url.trim());
      httpPost.setHeader(new BasicHeader("Content-type", "application/x-www-form-urlencoded"));
      List<NameValuePair> list = new ArrayList<NameValuePair>();
      list.add(new BasicNameValuePair("email", "123456789@163.com"));
      list.add(new BasicNameValuePair("password", "123456"));
      httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
      HttpResponse response = httpClient.execute(httpPost);
      找到需要设定的cookie
      Header[] headers = response.getHeaders("Set-Cookie");
      HashMap<String, String> cookies = new HashMap<String, String>(2);
      for (Header header : headers) {
        if (header.getValue().contains("_yapi_token")) {
          String token = header.getValue()
              .substring(header.getValue().indexOf("=") + 1, header.getValue().indexOf(';'));
          cookies.put("_yapi_token", token);
        } else if (header.getValue().contains("_yapi_uid")) {
          String uid = header.getValue()
              .substring(header.getValue().indexOf("=") + 1, header.getValue().indexOf(';'));
          cookies.put("_yapi_uid", uid);
        }
      }

使用cookie
这里是模拟登录yapi接口登记平台,需要取出的cookie值是 _yapi_token 和 _yapi_uid。接下来就是携带cookie登录。

    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionTimeToLive(6000, TimeUnit.MILLISECONDS).build();
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    BasicClientCookie tokenCookie = new BasicClientCookie("_yapi_token",
        cookies.get("_yapi_token"));
    tokenCookie.setPath("/");
    tokenCookie.setExpiryDate(new Date(System.currentTimeMillis() + 60 * 60 * 1000));
    BasicClientCookie uidCookies = new BasicClientCookie("_yapi_uid", cookies.get("_yapi_uid"));
    uidCookies.setExpiryDate(new Date(System.currentTimeMillis() + 60 * 60 * 1000));
    uidCookies.setPath("/");
    cookieStore.addCookie(tokenCookie);
    cookieStore.addCookie(uidCookies);
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Cookie", cookieStore.toString());
    CloseableHttpResponse response = httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() == HTTP_OK) {
      return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.displayName());
    } else {
      return String.valueOf(response.getStatusLine().getStatusCode());
    }

HttpClient 4.x 库可以自己处理Cookie
两种方式可以添加cookie,

  • 1.通过 httpclient.setCookieStore(cookieStore)
  • 2.通过 httpGet 或者 httpPost 的addHeader(new BasicHeader(“Cookie”,cookie));

这里两种都使用使用,

第一种方法
在httpClient 4.x中已经支持自动储存cookie,在下次访问时只需要设置参数,是否携带cookie(但是httpClient.getParams在最新api已经是被抛弃的了,使用不太推荐使用第一种)

httpclient.getParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH)

或者

CookiePolicy.BROWSER_COMPATIBILITY 

假如使用的httpClient和上面使用的已经不是同一个需要手工设置cookie;
通过httpclient.setCookieStore(cookieStore) 去设置;

第二张方法(推荐使用),直接在http请求的head里面携带cookie。

httpGet.addHeader("Cookie", cookieStore.toString());
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值