cookie&HTTPS

1、默认情况下,httpclient会默认引用cookieStore(同一个client的情况下) 自动存储和记录在client生命周期之内得到的cookie。在之后的发包操作中会自动的将cookie携带在头域中进行请求。

 但是两个不同的client会使用不同的cookie,如果需要两个不同的client使用相同的 cookie,可以在创建 client 时传入同一个 cookieStore,如下

//创建cookieStore存储cookie
CookieStore cookieStore=new BasicCookieStore();

CloseableHttpClient client1=HttpClients.custom().setDefaultCookieStore(cookieStore).build();
CloseableHttpClient client2=HttpClients.custom().setDefaultCookieStore(cookieStore).build();

2、cookieStore添加 cookie

//创建cookieStore存储cookie
CookieStore cookieStore=new BasicCookieStore();
//创建cookie对象
Cookie cookie=new BasicClientCookie("BIDUPSID","9E9076941C4F683E0D1465223ECA3650");

cookieStore.addCookie(cookie);

3、访问HTTPS,不进行证书校验

    public static CloseableHttpClient wrapClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");

            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom().setSSLSocketFactory(ssf).build();
        } catch (Exception e) {
            return HttpClients.createDefault();
        }
    }

 

posted @ 2020-01-02 00:12  hjy1995  阅读(418)  评论(0编辑  收藏  举报