旧版本DefaultHttpClient 使用getCookieStore可以直接获取cookies信息,但apache升级4.5后,DefaultHttpClient过期了,可以使用CloseableHttpClient做为替换获取cookies,代码如下:
//存储cookies信息变量
CookieStore store = new BasicCookieStore();
//设置cookies信息
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
//获取cookies信息
List<Cookie> cookieList = store.getCookies();
for (Cookie cookie:cookieList) {
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookie name = " + name
+ "; cookie value = " + value);
}
另,在HttpClientBuilder中有很多属性和方法可用,例如
private HttpRequestExecutor requestExec;
private HostnameVerifier hostnameVerifier;
private LayeredConnectionSocketFactory sslSocketFactory;
private SSLContext sslContext;
private HttpClientConnectionManager connManager;
private boolean connManagerShared;
private SchemePortResolver schemePortResolver;
private ConnectionReuseStrategy reuseStrategy;
private ConnectionKeepAliveStrategy keepAliveStrategy;
private AuthenticationStrategy targetAuthStrategy;
private AuthenticationStrategy proxyAuthStrategy;
private UserTokenHandler userTokenHandler;
private HttpProcessor httpprocessor;
private DnsResolver dnsResolver;
private LinkedList<HttpRequestInterceptor> requestFirst;
private LinkedList<HttpRequestInterceptor> requestLast;
private LinkedList<HttpResponseInterceptor> responseFirst;
private LinkedList<HttpResponseInterceptor> responseLast;
private HttpRequestRetryHandler retryHandler;
private HttpRoutePlanner routePlanner;
private RedirectStrategy redirectStrategy;
private ConnectionBackoffStrategy connectionBackoffStrategy;
private BackoffManager backoffManager;
private ServiceUnavailableRetryStrategy serviceUnavailStrategy;
private Lookup<AuthSchemeProvider> authSchemeRegistry;
private Lookup<CookieSpecProvider> cookieSpecRegistry;
private Map<String, InputStreamFactory> contentDecoderMap;
private CookieStore cookieStore;
private CredentialsProvider credentialsProvider;
private String userAgent;
private HttpHost proxy;
private Collection<? extends Header> defaultHeaders;
private SocketConfig defaultSocketConfig;
private ConnectionConfig defaultConnectionConfig;
private RequestConfig defaultRequestConfig;
private boolean evictExpiredConnections;
private boolean evictIdleConnections;
private long maxIdleTime;
private TimeUnit maxIdleTimeUnit;
private boolean systemProperties;
private boolean redirectHandlingDisabled;
private boolean automaticRetriesDisabled;
private boolean contentCompressionDisabled;
private boolean cookieManagementDisabled;
private boolean authCachingDisabled;
private boolean connectionStateDisabled;
private int maxConnTotal = 0;
private int maxConnPerRoute = 0;
private long connTimeToLive = -1L;
private TimeUnit connTimeToLiveTimeUnit;
private List<Closeable> closeables;
private PublicSuffixMatcher publicSuffixMatcher;