简体   繁体   中英

Using apache httpclient how to set cookie for http request

I am trying to set abc=123 cookie before sending http request.

In the response I am expecting the same cookie to be sent back. But in the response I get abc=890 where the value is set by the target server.

        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());

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM