apache httpclient cookies management
In order to manage cookies with Apache HttpClient, you can use the CookieStore
interface and the BasicCookieStore
implementation provided by the library.
Here's an example that demonstrates how to use CookieStore
to manage cookies:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HttpClientExample { public static void main(String[] args) throws Exception { String loginUrl = "http://www.example.com/login"; String username = "username"; String password = "password"; CookieStore cookieStore = new BasicCookieStore(); HttpClient httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .build(); HttpPost httpPost = new HttpPost(loginUrl); List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); httpPost.setEntity(new UrlEncodedFormEntity(params)); httpClient.execute(httpPost); HttpGet httpGet = new HttpGet("http://www.example.com/"); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); System.out.println(responseBody); } List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { System.out.println("Cookie: " + cookie.getName() + ", Value: " + cookie.getValue()); } } }
In this example, we first create a CookieStore
object using the BasicCookieStore
class. We then create an instance of HttpClientBuilder
and set the CookieStore
object as the default cookie store for the HttpClient
object using the setDefaultCookieStore()
method. Next, we execute a login request using an HttpPost
object and store the returned cookies in the CookieStore
object.
After authentication, we create an HttpGet
object and execute it using the HttpClient
object. We then extract the response body using the EntityUtils
class.
Finally, we use the getCookies()
method of the CookieStore
object to retrieve the cookies returned by the server, and print out the names and values of each cookie.
Note that by default, BasicCookieStore
stores all cookies in memory. If you need to persist cookies across multiple sessions, you may want to consider using a different implementation of the CookieStore
interface.