首页 > 解决方案 > HttpClient没有将所有cookie发送到restful api

问题描述

我正在使用 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。我错过了什么?请帮忙。

标签: javaapacheapache-httpclient-4.x

解决方案


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

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

正如评论中所建议的,您也没有添加cookiestore到上下文中。

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

上面代码的另一个问题是

basicClientCookie.setDomain(cookie.getDomain());

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


推荐阅读