Search in sources :

Example 46 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, NotificationFormat nFormat, String curWaitSetID, ResponseHandler respHandler) throws IOException, ServiceException {
    HttpPost method = null;
    HttpClient client = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri = getUriWithPath(document);
        method = new HttpPost(uri);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.addHeader(new BasicHeader("User-Agent", agentName));
        }
        // Set the original user agent if it's specified.
        String originalUserAgent = getOriginalUserAgent();
        if (originalUserAgent != null) {
            method.addHeader(new BasicHeader(HeaderConstants.HTTP_HEADER_ORIG_USER_AGENT, originalUserAgent));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.addHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.addHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType, nFormat, curWaitSetID);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        method.setEntity(new StringEntity(soapMessage, ContentType.create(ContentType.APPLICATION_XML.getMimeType(), "UTF-8")));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.addHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.addHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        ZAuthToken zToken = getAuthToken();
        BasicCookieStore cookieStore = HttpClientUtil.newHttpState(zToken, host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken);
            cookie.setDomain(host);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookieStore.addCookie(cookie);
        }
        if (zToken instanceof ZJWToken) {
            method.addHeader(Constants.AUTH_HEADER, Constants.BEARER + " " + zToken.getValue());
        }
        ZimbraLog.soap.trace("Httpclient timeout: %s", mTimeout);
        RequestConfig reqConfig = RequestConfig.custom().setCookieSpec(cookieStore.getCookies().size() == 0 ? CookieSpecs.IGNORE_COOKIES : CookieSpecs.BROWSER_COMPATIBILITY).setSocketTimeout(mTimeout).build();
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(mTimeout).setTcpNoDelay(LC.httpclient_external_connmgr_tcp_nodelay.booleanValue()).build();
        method.setProtocolVersion(HttpVersion.HTTP_1_1);
        method.addHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        client = mClientBuilder.setDefaultRequestConfig(reqConfig).setDefaultSocketConfig(socketConfig).setDefaultCookieStore(cookieStore).build();
        ZimbraLog.soap.trace("Httpclient request config timeout: %s", reqConfig.getSocketTimeout());
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            Credentials credentials = new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword());
            AuthScope authScope = new AuthScope(null, -1);
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(authScope, credentials);
            client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(reqConfig).setDefaultSocketConfig(socketConfig).setDefaultCookieStore(cookieStore).build();
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, cookieStore);
        }
        HttpResponse response = client.execute(method);
        int responseCode = response.getStatusLine().getStatusCode();
        // real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(response.getStatusLine().getReasonPhrase(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                HttpEntity httpEntity = response.getEntity();
                httpEntity.getContentLength();
                responseStr = ByteUtil.getContent(reader, (int) httpEntity.getContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            ZimbraHttpConnectionManager.getInternalHttpConnMgr().closeIdleConnections();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) InputStreamReader(java.io.InputStreamReader) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ZAuthToken(com.zimbra.common.auth.ZAuthToken) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ZJWToken(com.zimbra.common.auth.ZJWToken) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) Map(java.util.Map) HashMap(java.util.HashMap) BasicHeader(org.apache.http.message.BasicHeader) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 47 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project zm-mailbox by Zimbra.

the class WebDavClient method setAuthCookie.

public void setAuthCookie(ZAuthToken auth) {
    Map<String, String> cookieMap = auth.cookieMap(false);
    if (cookieMap != null) {
        String host = null;
        try {
            host = new URL(mBaseUrl).getHost();
        } catch (Exception e) {
        }
        BasicCookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
            cookie.setDomain(host);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookieStore.addCookie(cookie);
        }
        mClient.setDefaultCookieStore(cookieStore);
        RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        mClient.setDefaultRequestConfig(reqConfig);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Map(java.util.Map) URL(java.net.URL) XmlParseException(com.zimbra.common.soap.XmlParseException) HttpException(org.apache.http.HttpException) IOException(java.io.IOException) DavException(com.zimbra.cs.dav.DavException)

Example 48 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project zm-mailbox by Zimbra.

the class LmcMessage method downloadAttachment.

public byte[] downloadAttachment(String partNo, String baseURL, LmcSession session, String cookieDomain, int msTimeout) throws Exception {
    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcMessage.downloadAttachment session=null");
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    String url = baseURL + "?id=" + getID() + "&part=" + partNo;
    HttpGet get = new HttpGet(url);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        BasicCookieStore initialState = new BasicCookieStore();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
            cookie.setDomain(cookieDomain);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookie.setExpiryDate(null);
            initialState.addCookie(cookie);
        }
        clientBuilder.setDefaultCookieStore(initialState);
        RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        clientBuilder.setDefaultRequestConfig(reqConfig);
    }
    SocketConfig config = SocketConfig.custom().setSoTimeout(msTimeout).build();
    clientBuilder.setDefaultSocketConfig(config);
    HttpClient client = clientBuilder.build();
    int statusCode = -1;
    try {
        HttpResponse response = HttpClientUtil.executeMethod(client, get);
        // parse the response
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            throw new LmcSoapClientException("Attachment download failed, status=" + statusCode);
        }
    } catch (IOException | HttpException e) {
        System.err.println("Attachment download failed");
        e.printStackTrace();
        throw e;
    } finally {
        get.releaseConnection();
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) LmcSoapClientException(com.zimbra.cs.client.soap.LmcSoapClientException) SocketConfig(org.apache.http.config.SocketConfig) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) IOException(java.io.IOException) ZAuthToken(com.zimbra.common.auth.ZAuthToken) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.http.HttpException) Map(java.util.Map)

Example 49 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project SmartAndroidSource by jaychou2012.

the class AbstractAjaxCallback method httpDo.

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = client.execute(hr, context);
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);
    File file = null;
    if (code < 200 || code >= 300) {
        try {
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            // AQUtility.time("copy");
            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
            // AQUtility.timeEnd("copy", 0);
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 50 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project ribbon by Netflix.

the class RestClient method apacheHttpClientSpecificInitialization.

protected Client apacheHttpClientSpecificInitialization() {
    httpClient4 = NFHttpClientFactory.getNamedNFHttpClient(restClientName, this.ncc, true);
    if (httpClient4 instanceof AbstractHttpClient) {
        // DONT use our NFHttpClient's default Retry Handler since we have
        // retry handling (same server/next server) in RestClient itself
        ((AbstractHttpClient) httpClient4).setHttpRequestRetryHandler(new NFHttpMethodRetryHandler(restClientName, 0, false, 0));
    } else {
        logger.warn("Unexpected error: Unable to disable NFHttpClient " + "retry handler, this most likely will not cause an " + "issue but probably should be looked at");
    }
    HttpParams httpClientParams = httpClient4.getParams();
    // initialize Connection Manager cleanup facility
    NFHttpClient nfHttpClient = (NFHttpClient) httpClient4;
    // should we enable connection cleanup for idle connections?
    try {
        enableConnectionPoolCleanerTask = ncc.getOrDefault(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled);
        nfHttpClient.getConnPoolCleaner().setEnableConnectionPoolCleanerTask(enableConnectionPoolCleanerTask);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, e1);
    }
    if (enableConnectionPoolCleanerTask) {
        try {
            connectionCleanerRepeatInterval = ncc.getOrDefault(CommonClientConfigKey.ConnectionCleanerRepeatInterval);
            nfHttpClient.getConnPoolCleaner().setConnectionCleanerRepeatInterval(connectionCleanerRepeatInterval);
        } catch (Exception e1) {
            throwInvalidValue(CommonClientConfigKey.ConnectionCleanerRepeatInterval, e1);
        }
        try {
            connIdleEvictTimeMilliSeconds = ncc.getDynamicProperty(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds);
            nfHttpClient.setConnIdleEvictTimeMilliSeconds(connIdleEvictTimeMilliSeconds);
        } catch (Exception e1) {
            throwInvalidValue(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, e1);
        }
        nfHttpClient.initConnectionCleanerTask();
    }
    try {
        maxConnectionsperHost = ncc.getOrDefault(CommonClientConfigKey.MaxHttpConnectionsPerHost);
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setDefaultMaxPerRoute(maxConnectionsperHost);
        }
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.MaxHttpConnectionsPerHost, e1);
    }
    try {
        maxTotalConnections = ncc.getOrDefault(CommonClientConfigKey.MaxTotalHttpConnections);
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setMaxTotal(maxTotalConnections);
        }
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.MaxTotalHttpConnections, e1);
    }
    try {
        connectionTimeout = ncc.getOrDefault(CommonClientConfigKey.ConnectTimeout);
        HttpConnectionParams.setConnectionTimeout(httpClientParams, connectionTimeout);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ConnectTimeout, e1);
    }
    try {
        readTimeout = ncc.getOrDefault(CommonClientConfigKey.ReadTimeout);
        HttpConnectionParams.setSoTimeout(httpClientParams, readTimeout);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ReadTimeout, e1);
    }
    // httpclient 4 seems to only have one buffer size controlling both
    // send/receive - so let's take the bigger of the two values and use
    // it as buffer size
    int bufferSize = Integer.MIN_VALUE;
    if (ncc.get(CommonClientConfigKey.ReceiveBufferSize) != null) {
        try {
            bufferSize = ncc.getOrDefault(CommonClientConfigKey.ReceiveBufferSize);
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.ReceiveBufferSize, e);
        }
        if (ncc.get(CommonClientConfigKey.SendBufferSize) != null) {
            try {
                int sendBufferSize = ncc.getOrDefault(CommonClientConfigKey.SendBufferSize);
                if (sendBufferSize > bufferSize) {
                    bufferSize = sendBufferSize;
                }
            } catch (Exception e) {
                throwInvalidValue(CommonClientConfigKey.SendBufferSize, e);
            }
        }
    }
    if (bufferSize != Integer.MIN_VALUE) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams, bufferSize);
    }
    if (ncc.get(CommonClientConfigKey.StaleCheckingEnabled) != null) {
        try {
            HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.StaleCheckingEnabled));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.StaleCheckingEnabled, e);
        }
    }
    if (ncc.get(CommonClientConfigKey.Linger) != null) {
        try {
            HttpConnectionParams.setLinger(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.Linger));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.Linger, e);
        }
    }
    if (ncc.get(CommonClientConfigKey.ProxyHost) != null) {
        try {
            proxyHost = (String) ncc.getOrDefault(CommonClientConfigKey.ProxyHost);
            proxyPort = ncc.getOrDefault(CommonClientConfigKey.ProxyPort);
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClient4.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.ProxyHost, e);
        }
    }
    if (isSecure) {
        final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore);
        final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore);
        final ClientConnectionManager currentManager = httpClient4.getConnectionManager();
        AbstractSslContextFactory abstractFactory = null;
        if (// if client is not is not required, we only need a keystore OR a truststore to warrant configuring
        (isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null)) || (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null))) {
            try {
                abstractFactory = new URLSslContextFactory(trustStoreUrl, ncc.get(CommonClientConfigKey.TrustStorePassword), keyStoreUrl, ncc.get(CommonClientConfigKey.KeyStorePassword));
            } catch (ClientSslSocketFactoryException e) {
                throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
            }
        }
        KeyStoreAwareSocketFactory awareSocketFactory;
        try {
            awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractFactory) : new KeyStoreAwareSocketFactory(abstractFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            currentManager.getSchemeRegistry().register(new Scheme("https", 443, awareSocketFactory));
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
        }
    }
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html
    if (ignoreUserToken) {
        ((DefaultHttpClient) httpClient4).setUserTokenHandler(new UserTokenHandler() {

            @Override
            public Object getUserToken(HttpContext context) {
                return null;
            }
        });
    }
    // custom SSL Factory handler
    String customSSLFactoryClassName = ncc.get(CommonClientConfigKey.CustomSSLSocketFactoryClassName);
    if (customSSLFactoryClassName != null) {
        try {
            SSLSocketFactory customSocketFactory = (SSLSocketFactory) ClientFactory.instantiateInstanceWithClientConfig(customSSLFactoryClassName, ncc);
            httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, customSocketFactory));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.CustomSSLSocketFactoryClassName, e);
        }
    }
    ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpClient4, new BasicCookieStore(), false);
    return new ApacheHttpClient4(handler, config);
}
Also used : ApacheHttpClient4Handler(com.sun.jersey.client.apache4.ApacheHttpClient4Handler) Scheme(org.apache.http.conn.scheme.Scheme) AbstractSslContextFactory(com.netflix.client.ssl.AbstractSslContextFactory) NFHttpClient(com.netflix.http4.NFHttpClient) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) KeyStoreAwareSocketFactory(com.netflix.http4.ssl.KeyStoreAwareSocketFactory) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) ApacheHttpClient4(com.sun.jersey.client.apache4.ApacheHttpClient4) UserTokenHandler(org.apache.http.client.UserTokenHandler) NFHttpMethodRetryHandler(com.netflix.http4.NFHttpMethodRetryHandler) ClientSslSocketFactoryException(com.netflix.client.ssl.ClientSslSocketFactoryException) HttpContext(org.apache.http.protocol.HttpContext) URLSslContextFactory(com.netflix.client.ssl.URLSslContextFactory) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) URISyntaxException(java.net.URISyntaxException) ClientException(com.netflix.client.ClientException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) ClientSslSocketFactoryException(com.netflix.client.ssl.ClientSslSocketFactoryException) AbstractHttpClient(org.apache.http.impl.client.AbstractHttpClient) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)

Aggregations

BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)138 HttpResponse (org.apache.http.HttpResponse)54 HttpGet (org.apache.http.client.methods.HttpGet)51 Test (org.junit.Test)44 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)40 RequestConfig (org.apache.http.client.config.RequestConfig)36 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 CookieStore (org.apache.http.client.CookieStore)26 Header (org.apache.http.Header)25 HttpClient (org.apache.http.client.HttpClient)25 IOException (java.io.IOException)23 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)22 Cookie (org.apache.http.cookie.Cookie)19 HttpPost (org.apache.http.client.methods.HttpPost)15 CredentialsProvider (org.apache.http.client.CredentialsProvider)14 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)14 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)14 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)13 URI (java.net.URI)12 HttpEntity (org.apache.http.HttpEntity)12