Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apache httpclient how to set cookie for http request

Tags:

java

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

like image 651
SUM Avatar asked Jan 02 '13 00:01

SUM


People also ask

How do you add a cookie to an HTTP request in Java?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.


1 Answers

It worked after adding

cookie.setDomain(".xyz.net");
cookie.setPath("/");
like image 137
SUM Avatar answered Sep 26 '22 12:09

SUM