CloseableHttpClient 存储cookie
时间: 2023-11-05 15:22:10 浏览: 121
CloseableHttpClient 是 Apache HttpClient 库中的一个类,用于发送 HTTP 请求和接收响应。要在 CloseableHttpClient 中存储 cookie,可以使用 HttpClientContext 类的 setCookieStore() 方法。
下面是一个简单的示例代码,演示如何在 CloseableHttpClient 中存储 cookie:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.CloseableHttpRequestBase;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
HttpGet httpGet = new HttpGet("https://www.example.com");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
// 根据需要处理响应内容
// 获取存储的 cookie
System.out.println("Stored cookies:");
cookieStore.getCookies().forEach(System.out::println);
}
}
}
```
以上代码创建了一个 CloseableHttpClient 对象,并设置了一个 BasicCookieStore 对象作为默认的 Cookie 存储。然后执行了一个 GET 请求,并获取了响应内容。最后,使用 cookieStore.getCookies() 方法获取存储的 cookie。
请根据实际需求进行修改和扩展。希望以上信息对你有所帮助!如果有任何问题,请随时提问。
阅读全文