Search in sources :

Example 11 with HttpParams

use of org.apache.http.params.HttpParams in project ribbon by Netflix.

the class NFHttpClient method init.

void init(IClientConfig config, boolean registerMonitor) {
    HttpParams params = getParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ThreadSafeClientConnManager.class.getName());
    HttpClientParams.setRedirecting(params, config.getPropertyAsBoolean(CommonClientConfigKey.FollowRedirects, true));
    // set up default headers
    List<Header> defaultHeaders = new ArrayList<Header>();
    defaultHeaders.add(new BasicHeader("Netflix.NFHttpClient.Version", "1.0"));
    defaultHeaders.add(new BasicHeader("X-netflix-httpclientname", name));
    params.setParameter(ClientPNames.DEFAULT_HEADERS, defaultHeaders);
    connPoolCleaner = new ConnectionPoolCleaner(name, this.getConnectionManager(), connectionPoolCleanUpScheduler);
    this.retriesProperty = DynamicPropertyFactory.getInstance().getIntProperty(this.name + ".nfhttpclient" + ".retries", 3);
    this.sleepTimeFactorMsProperty = DynamicPropertyFactory.getInstance().getIntProperty(this.name + ".nfhttpclient" + ".sleepTimeFactorMs", 10);
    setHttpRequestRetryHandler(new NFHttpMethodRetryHandler(this.name, this.retriesProperty.get(), false, this.sleepTimeFactorMsProperty.get()));
    tracer = Monitors.newTimer(EXECUTE_TRACER + "-" + name, TimeUnit.MILLISECONDS);
    if (registerMonitor) {
        Monitors.registerObject(name, this);
    }
    maxTotalConnectionProperty = new DynamicIntProperty(this.name + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxTotalHttpConnections.key(), DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_HTTP_CONNECTIONS);
    maxTotalConnectionProperty.addCallback(new Runnable() {

        @Override
        public void run() {
            ((ThreadSafeClientConnManager) getConnectionManager()).setMaxTotal(maxTotalConnectionProperty.get());
        }
    });
    maxConnectionPerHostProperty = new DynamicIntProperty(this.name + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxHttpConnectionsPerHost.key(), DefaultClientConfigImpl.DEFAULT_MAX_HTTP_CONNECTIONS_PER_HOST);
    maxConnectionPerHostProperty.addCallback(new Runnable() {

        @Override
        public void run() {
            ((ThreadSafeClientConnManager) getConnectionManager()).setDefaultMaxPerRoute(maxConnectionPerHostProperty.get());
        }
    });
}
Also used : HttpParams(org.apache.http.params.HttpParams) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHeader(org.apache.http.message.BasicHeader) DynamicIntProperty(com.netflix.config.DynamicIntProperty)

Example 12 with HttpParams

use of org.apache.http.params.HttpParams in project OpenAttestation by OpenAttestation.

the class SslUtil method getServerCertificates.

public static X509Certificate[] getServerCertificates(URL url) throws NoSuchAlgorithmException, KeyManagementException, IOException {
    if (!"https".equals(url.getProtocol())) {
        throw new IllegalArgumentException("URL scheme must be https");
    }
    int port = url.getPort();
    if (port == -1) {
        port = 443;
    }
    X509HostnameVerifier hostnameVerifier = new NopX509HostnameVerifierApache();
    CertificateStoringX509TrustManager trustManager = new CertificateStoringX509TrustManager();
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new X509TrustManager[] { trustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier);
    Scheme https = new Scheme("https", port, sf);
    SchemeRegistry sr = new SchemeRegistry();
    sr.register(https);
    BasicClientConnectionManager connectionManager = new BasicClientConnectionManager(sr);
    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    HttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
    log.debug("Saving certificates from server URL: {}", url.toExternalForm());
    HttpHead request = new HttpHead(url.toExternalForm());
    HttpResponse response = httpClient.execute(request);
    log.debug("Server status line: {} {} ({})", new String[] { response.getProtocolVersion().getProtocol(), response.getStatusLine().getReasonPhrase(), String.valueOf(response.getStatusLine().getStatusCode()) });
    httpClient.getConnectionManager().shutdown();
    return trustManager.getStoredCertificates();
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHead(org.apache.http.client.methods.HttpHead) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 13 with HttpParams

use of org.apache.http.params.HttpParams in project openkit-android by OpenKit.

the class AsyncHttpClient method setTimeout.

/**
     * Sets the connection time oout. By default, 10 seconds
     * @param timeout the connect/socket timeout in milliseconds
     */
public void setTimeout(int timeout) {
    final HttpParams httpParams = this.httpClient.getParams();
    ConnManagerParams.setTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams)

Example 14 with HttpParams

use of org.apache.http.params.HttpParams in project OpenMEAP by OpenMEAP.

the class SSLUtils method getRelaxedSSLVerificationHttpClient.

public static HttpClient getRelaxedSSLVerificationHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, FormConstants.CHAR_ENC_DEFAULT);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams) KeyStore(java.security.KeyStore) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 15 with HttpParams

use of org.apache.http.params.HttpParams 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)

Aggregations

HttpParams (org.apache.http.params.HttpParams)121 BasicHttpParams (org.apache.http.params.BasicHttpParams)85 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)43 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)31 Scheme (org.apache.http.conn.scheme.Scheme)30 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)28 IOException (java.io.IOException)27 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)27 HttpResponse (org.apache.http.HttpResponse)24 HttpHost (org.apache.http.HttpHost)23 Header (org.apache.http.Header)18 HttpGet (org.apache.http.client.methods.HttpGet)13 URI (java.net.URI)10 HttpRequest (org.apache.http.HttpRequest)10 HttpClient (org.apache.http.client.HttpClient)10 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)10 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)10 Socket (java.net.Socket)9 ClientProtocolException (org.apache.http.client.ClientProtocolException)9 GeneralSecurityException (java.security.GeneralSecurityException)8