简体   繁体   English

使用apache httpclient如何为http请求设置cookie

[英]Using apache httpclient how to set cookie for http request

I am trying to set abc=123 cookie before sending http request. 我想在发送http请求之前设置abc = 123 cookie。

In the response I am expecting the same cookie to be sent back. 在回复中,我希望将相同的cookie发回。 But in the response I get abc=890 where the value is set by the target server. 但是在响应中我得到abc = 890,其中值由目标服务器设置。

        DefaultHttpClient httpclient = new DefaultHttpClient();
    CookieStore cookieStore = httpclient.getCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("abc", "123");

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://abc.net/restofurl");

    cookieStore.addCookie(cookie);
    httpclient.setCookieStore(cookieStore);

    // Execute the request
    HttpResponse response = httpclient.execute(httpget);

    // Examine the response status
    log.info("Http request response is: " + response.getStatusLine());

    List<Cookie> cookies = cookieStore.getCookies();

    for (int i=0; i<cookies.size();i++) {

        if (cookies.get(i).getName().toString().equals("abc")) {
            log.info("cookie is: " + cookies.get(0).getValue().toString());
            }
    }

Thanks 谢谢

It worked after adding 添加后它起作用了

cookie.setDomain(".xyz.net");
cookie.setPath("/");

Is the problem resolved by changing 是通过改变来解决问题的

log.info("cookie is: " + cookies.get(0).getValue().toString());

into

log.info("cookie is: " + cookies.get(i).getValue().toString());

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Apache HttpComponents HttpClient设置&#39;Referer&#39;HTTP头 - How to set 'Referer' HTTP header using Apache HttpComponents HttpClient 如何使用apache httpclient fluent 4.3.2在请求中设置charset - How to set the charset in request using apache httpclient fluent 4.3.2 使用Apache HttpClient如何在请求和响应上设置TIMEOUT - Using Apache HttpClient how to set the TIMEOUT on a request and response 如何使用Apache httpclient 4. *和PoolingHttpClientConnectionManager为每个请求设置超时? - How to set timeout for each request using Apache httpclient 4.* with PoolingHttpClientConnectionManager? Apache HttpClient 4.0.3 - 如何为 POST 请求设置带有 sessionID 的 cookie? - Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request? 如何使用HTTPClient设置HTTP请求标头“身份验证”? - How to set HTTP Request Header “authentication” using HTTPClient? "如何使用 Apache HttpClient 发布 JSON 请求?" - How to POST JSON request using Apache HttpClient? 使用 Apache HttpClient 发送带有 SSL 身份验证的 HTTP 请求 - Sending HTTP request with SSL authontication using Apache HttpClient 如何为Apache HttpClient设置全局HTTP代理设置 - How to set global http proxy settings for apache HttpClient 使用Apache HttpClient的SOAP请求 - SOAP request using Apache HttpClient
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM