【问题标题】:HttpClient not sending all cookies to restful apiHttpClient 未将所有 cookie 发送到 restful api
【发布时间】:2018-06-16 02:09:49
【问题描述】:

我正在使用 HttpClient 4.4.1 调用一个 restful api,但它没有发送 cookie,

private CloseableHttpResponse call(String url, javax.servlet.http.HttpServletRequest httpServletRequest) {

    HttpGet request = new HttpGet(url);
    BasicHttpContext localContext = new BasicHttpContext();

    CookieStore cookieStore = new BasicCookieStore();
    javax.servlet.http.Cookie[] cookies = httpServletRequest.getCookies();
    BasicClientCookie basicClientCookie = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie cookie = cookies[i];
            basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
            basicClientCookie.setDomain(cookie.getDomain());
            basicClientCookie.setPath("/");
            basicClientCookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
            basicClientCookie.setVersion(0);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, 100);
            Date date = calendar.getTime();
            basicClientCookie.setExpiryDate(date);
            cookieStore.addCookie(basicClientCookie);
        }
    }
    if (cookieStore.getCookies() != null) {
      System.out.println("Cookies size " + cookieStore.getCookies().size());
    }
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(request, localContext);
    } catch (IOException e) {
        System.out.println("msg " + e.getMessage());

    }
    return httpResponse;
}

我可以看到它只发送已添加的最后一个 cookie。我错过了什么?请帮忙。

【问题讨论】:

  • 填充cookieStore 后,您在哪里使用它?另外,cookies 是否拥有您需要发送的所有 cookie?尝试打印它的大小。
  • 是的,它会将 cookie 大小打印为 13(正确大小)

标签: java apache apache-httpclient-4.x


【解决方案1】:

问题肯定出在 for 循环内的代码中,因为只有最后添加的 cookie 是可见的。

尝试使用调试器或在从请求中获取 cookies 数组时在循环前添加 system.out.println 语句来调试 for 循环,而不是在创建基本客户端 cookie 时在循环内,然后在添加基本客户端 cookie 到 cookiestore

根据 cmets 的建议,您也没有将 cookiestore 添加到上下文中。

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

上面代码的另一个问题是

basicClientCookie.setDomain(cookie.getDomain());

cookie.getDomain() 和 request 的 url 可以不同,根据 cookie 的行为,它们应该是相同的,那么只有 cookie 会发送。所以只有具有相同 url 的 cookie 才会随请求一起发送

【讨论】:

  • 更新问题,将cookiestore添加到localcontext。但仍然只发送最后一个 cookie。
  • 同时打印每个cookie的域和get请求的url。它们应该有相同的域
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
相关资源
最近更新 更多