欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient模拟带Cookie的登录请求

程序员文章站 2022-05-07 12:09:01
...

转载自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", "[email protected]"));
      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());