How to convert Apache cookies back to String?

1.7k views Asked by At

Here is my code:

 List<Cookie> cookies = httpClient.getCookieStore().getCookies();

Obviously, I can loop the cookies list and generate their String representation.

However, I wonder if it can be done with the Apache HttpClient API directly.

So if cookiescontain the following cookies: [foo=123, bar=123], how can I generate the String below with HttpClient API:

"foo=123; bar=123"

The method should take care of domain, path, expiration etc

HttpClient 4.1.1

1

There are 1 answers

2
ok2c On BEST ANSWER

HttpClient 4.1

BasicClientCookie cookie1 = new BasicClientCookie("foo", "123");
cookie1.setVersion(0);
cookie1.setDomain("origin.com");
cookie1.setPath("/");
BasicClientCookie cookie2 = new BasicClientCookie("bar", "123");
cookie1.setVersion(0);
cookie1.setDomain("origin.com");
cookie1.setPath("/");

BasicCookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(cookie1);
cookieStore.addCookie(cookie2);

NetscapeDraftSpec spec = new NetscapeDraftSpec();
List<Header> headers = spec.formatCookies(cookieStore.getCookies());
for (Header header: headers) {
    System.out.println(header);
}

HttpClient 4.5

BasicClientCookie cookie1 = new BasicClientCookie("foo", "123");
cookie1.setVersion(0);
cookie1.setDomain("origin.com");
cookie1.setPath("/");
BasicClientCookie cookie2 = new BasicClientCookie("bar", "123");
cookie1.setVersion(0);
cookie1.setDomain("origin.com");
cookie1.setPath("/");

BasicCookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(cookie2);
cookieStore.addCookie(cookie1);

RFC6265StrictSpec spec = new RFC6265StrictSpec();
List<Header> headers = spec.formatCookies(cookieStore.getCookies());
for (Header header: headers) {
    System.out.println(header);
}