Search in sources :

Example 21 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project screenbird by adamhub.

the class FileUtil method postData.

public static String[] postData(String data, final JProgressBar pbUpload, String anonymous_token, String csrf_token, String user_id, ProgressBarUploadProgressListener listener, String upload_url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(upload_url);
    //File file = new File(fileLocation);
    //MultipartEntity mpEntity = new MultipartEntity();
    ProgressMultiPartEntity mpEntity = new ProgressMultiPartEntity(listener);
    //ContentBody cbFile = new FileBody(file, "video/quicktime");
    //mpEntity.addPart("videoupload", cbFile);
    //ContentBody cbToken = new StringBody(title);
    //mpEntity.addPart("csrfmiddlewaretoken", cbToken);
    ContentBody cbUser_id = new StringBody(user_id);
    mpEntity.addPart("user_id", cbUser_id);
    ContentBody cbAnonym_id = new StringBody(MediaUtil.getMacAddress());
    mpEntity.addPart("anonym_id", cbAnonym_id);
    //ContentBody cbTitle = new StringBody(title);
    //mpEntity.addPart("title", cbTitle);
    //        ContentBody cbSlug = new StringBody(slug);
    //        mpEntity.addPart("slug", cbSlug);
    //        ContentBody cbPublic = new StringBody(is_public ? "1" : "0");
    //        mpEntity.addPart("is_public", cbPublic);
    //        ContentBody cbDescription = new StringBody(description);
    //        mpEntity.addPart("description", cbDescription);
    //        ContentBody cbChecksum = new StringBody(checksum);
    //        mpEntity.addPart("checksum", cbChecksum);
    //        ContentBody cbType = new StringBody(video_type);
    //        mpEntity.addPart("video_type", cbType);
    httppost.setEntity(mpEntity);
    System.out.println("===================================================");
    System.out.println("executing request " + httppost.getRequestLine());
    System.out.println("===================================================");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    String[] result = new String[2];
    String status = response.getStatusLine().toString();
    result[0] = (status.indexOf("200") >= 0) ? "200" : status;
    System.out.println("===================================================");
    System.out.println("status from request " + result[0]);
    System.out.println("===================================================");
    if (resEntity != null) {
        result[1] = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);
    }
    httpclient.getConnectionManager().shutdown();
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) ProgressMultiPartEntity(com.bixly.pastevid.util.view.ProgressMultiPartEntity) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 22 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient 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 = Boolean.parseBoolean(ncc.getProperty(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, NFHttpClientConstants.DEFAULT_CONNECTIONIDLE_TIMETASK_ENABLED).toString());
        nfHttpClient.getConnPoolCleaner().setEnableConnectionPoolCleanerTask(enableConnectionPoolCleanerTask);
    } catch (Exception e1) {
        throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, e1);
    }
    if (enableConnectionPoolCleanerTask) {
        try {
            connectionCleanerRepeatInterval = Integer.parseInt(String.valueOf(ncc.getProperty(CommonClientConfigKey.ConnectionCleanerRepeatInterval, NFHttpClientConstants.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS)));
            nfHttpClient.getConnPoolCleaner().setConnectionCleanerRepeatInterval(connectionCleanerRepeatInterval);
        } catch (Exception e1) {
            throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnectionCleanerRepeatInterval, e1);
        }
        try {
            int iConnIdleEvictTimeMilliSeconds = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, NFHttpClientConstants.DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS));
            connIdleEvictTimeMilliSeconds = DynamicPropertyFactory.getInstance().getIntProperty(restClientName + ".nfhttpclient.connIdleEvictTimeMilliSeconds", iConnIdleEvictTimeMilliSeconds);
            nfHttpClient.setConnIdleEvictTimeMilliSeconds(connIdleEvictTimeMilliSeconds);
        } catch (Exception e1) {
            throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, e1);
        }
        nfHttpClient.initConnectionCleanerTask();
    }
    try {
        maxConnectionsperHost = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.MaxHttpConnectionsPerHost, maxConnectionsperHost));
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setDefaultMaxPerRoute(maxConnectionsperHost);
        }
    } catch (Exception e1) {
        throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.MaxHttpConnectionsPerHost, e1);
    }
    try {
        maxTotalConnections = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.MaxTotalHttpConnections, maxTotalConnections));
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setMaxTotal(maxTotalConnections);
        }
    } catch (Exception e1) {
        throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.MaxTotalHttpConnections, e1);
    }
    try {
        connectionTimeout = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ConnectTimeout, connectionTimeout));
        HttpConnectionParams.setConnectionTimeout(httpClientParams, connectionTimeout);
    } catch (Exception e1) {
        throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnectTimeout, e1);
    }
    try {
        readTimeout = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ReadTimeout, readTimeout));
        HttpConnectionParams.setSoTimeout(httpClientParams, readTimeout);
    } catch (Exception e1) {
        throw new IllegalArgumentException("Invalid value for property:" + 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.getProperty(CommonClientConfigKey.ReceiveBufferSize) != null) {
        try {
            bufferSize = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ReceiveBufferSize));
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ReceiveBufferSize, e);
        }
        if (ncc.getProperty(CommonClientConfigKey.SendBufferSize) != null) {
            try {
                int sendBufferSize = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.SendBufferSize));
                if (sendBufferSize > bufferSize) {
                    bufferSize = sendBufferSize;
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.SendBufferSize, e);
            }
        }
    }
    if (bufferSize != Integer.MIN_VALUE) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams, bufferSize);
    }
    if (ncc.getProperty(CommonClientConfigKey.StaleCheckingEnabled) != null) {
        try {
            HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, Boolean.parseBoolean(ncc.getProperty(CommonClientConfigKey.StaleCheckingEnabled, false).toString()));
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.StaleCheckingEnabled, e);
        }
    }
    if (ncc.getProperty(CommonClientConfigKey.Linger) != null) {
        try {
            HttpConnectionParams.setLinger(httpClientParams, Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.Linger)));
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.Linger, e);
        }
    }
    if (ncc.getProperty(CommonClientConfigKey.ProxyHost) != null) {
        try {
            proxyHost = (String) ncc.getProperty(CommonClientConfigKey.ProxyHost);
            proxyPort = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ProxyPort));
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClient4.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid value for property:" + 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, (String) ncc.getProperty(CommonClientConfigKey.TrustStorePassword), keyStoreUrl, (String) ncc.getProperty(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 = (String) ncc.getProperty(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) {
            throw new IllegalArgumentException("Invalid value associated with property:" + 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)

Example 23 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient 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 24 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project android_frameworks_base by ParanoidAndroid.

the class FsUtils method getHttpClient.

private static HttpClient getHttpClient() {
    if (sHttpClient == null) {
        HttpParams params = new BasicHttpParams();
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), ForwarderManager.HTTP_PORT));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), ForwarderManager.HTTPS_PORT));
        ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
        sHttpClient = new DefaultHttpClient(connectionManager, params);
        HttpConnectionParams.setSoTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
        HttpConnectionParams.setConnectionTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
    }
    return sHttpClient;
}
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) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 25 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project android_frameworks_base by ParanoidAndroid.

the class CookiesTest method testCookiesAreNotLogged.

/**
     * Test that we don't log potentially sensitive cookie values.
     * http://b/3095990
     */
public void testCookiesAreNotLogged() throws IOException, URISyntaxException {
    // enqueue an HTTP response with a cookie that will be rejected
    server.enqueue(new MockResponse().addHeader("Set-Cookie: password=secret; Domain=fake.domain"));
    server.play();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Logger logger = Logger.getLogger("org.apache.http");
    StreamHandler handler = new StreamHandler(out, new SimpleFormatter());
    logger.addHandler(handler);
    try {
        HttpClient client = new DefaultHttpClient();
        client.execute(new HttpGet(server.getUrl("/").toURI()));
        handler.close();
        String log = out.toString("UTF-8");
        assertTrue(log, log.contains("password"));
        assertTrue(log, log.contains("fake.domain"));
        assertFalse(log, log.contains("secret"));
    } finally {
        logger.removeHandler(handler);
    }
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) StreamHandler(java.util.logging.StreamHandler) SimpleFormatter(java.util.logging.SimpleFormatter) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Logger(java.util.logging.Logger) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)481 HttpResponse (org.apache.http.HttpResponse)293 HttpGet (org.apache.http.client.methods.HttpGet)227 HttpClient (org.apache.http.client.HttpClient)203 IOException (java.io.IOException)158 HttpPost (org.apache.http.client.methods.HttpPost)107 Test (org.junit.Test)86 HttpEntity (org.apache.http.HttpEntity)84 ClientProtocolException (org.apache.http.client.ClientProtocolException)64 InputStream (java.io.InputStream)60 Scheme (org.apache.http.conn.scheme.Scheme)53 BasicHttpParams (org.apache.http.params.BasicHttpParams)51 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)49 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)48 HttpParams (org.apache.http.params.HttpParams)47 ArrayList (java.util.ArrayList)45 URI (java.net.URI)43 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)38 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)38 InputStreamReader (java.io.InputStreamReader)37