Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getParams.

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:com.lee.sdk.utils.Utils.java

/**
*  http client//www .j a v a 2s .  c  o m
* 
* @param context
*            Context.
* @return ProxyHttpClient
*/
public static DefaultHttpClient createHttpClient(Context context) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // httpclient.getParams().setParameter("Accept-Encoding", "gzip");

    final int httpTimeout = 30000;
    final int socketTimeout = 50000;
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), httpTimeout);
    HttpConnectionParams.setSoTimeout(httpclient.getParams(), socketTimeout);
    return httpclient;
}

From source file:com.quantcast.measurement.service.QCDataUploader.java

String synchronousUploadEvents(Collection<QCEvent> events) {
    if (events == null || events.isEmpty())
        return null;

    String uploadId = QCUtility.generateUniqueId();

    JSONObject upload = new JSONObject();
    try {/*from  ww  w . j  a v a2  s  .  c o m*/
        upload.put(QC_UPLOAD_ID_KEY, uploadId);
        upload.put(QC_QCV_KEY, QCUtility.API_VERSION);
        upload.put(QCEvent.QC_APIKEY_KEY, QCMeasurement.INSTANCE.getApiKey());
        upload.put(QCEvent.QC_NETWORKCODE_KEY, QCMeasurement.INSTANCE.getNetworkCode());
        upload.put(QCEvent.QC_DEVICEID_KEY, QCMeasurement.INSTANCE.getDeviceId());

        JSONArray event = new JSONArray();
        for (QCEvent e : events) {
            event.put(new JSONObject(e.getParameters()));
        }
        upload.put(QC_EVENTS_KEY, event);
    } catch (JSONException e) {
        QCLog.e(TAG, "Error while encoding json.");
        return null;
    }

    int code;
    String url = QCUtility.addScheme(UPLOAD_URL_WITHOUT_SCHEME);
    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    defaultHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
    final BasicHttpContext localContext = new BasicHttpContext();

    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(upload.toString(), HTTP.UTF_8);
        post.setEntity(se);

        HttpParams params = new BasicHttpParams();
        params.setBooleanParameter("http.protocol.expect-continue", false);
        post.setParams(params);

        HttpResponse response = defaultHttpClient.execute(post, localContext);
        code = response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        QCLog.e(TAG, "Could not upload events", e);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure", e.toString(), null);
        code = HttpStatus.SC_REQUEST_TIMEOUT;
    }

    if (!isSuccessful(code)) {
        uploadId = null;
        QCLog.e(TAG, "Events not sent to server. Response code: " + code);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure",
                "Bad response from server. Response code: " + code, null);
    }
    return uploadId;
}

From source file:com.rastating.droidbeard.net.HttpClientManager.java

private DefaultHttpClient createThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager manager = client.getConnectionManager();
    HttpParams params = client.getParams();
    ThreadSafeClientConnManager threadSafeManager = new ThreadSafeClientConnManager(params,
            manager.getSchemeRegistry());
    return new DefaultHttpClient(threadSafeManager, params);
}

From source file:org.balloon_project.overflight.task.indexing.Indexing.java

private void checkEndpoint(Endpoint endpoint) {
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("query", CHECK_QUERY));
    String entities = URLEncodedUtils.format(nameValuePairs, "UTF-8");

    // endpoint has to end with '/'
    String url = endpoint.getSparqlEndpoint();

    if (url.endsWith("/")) {
        url += "?" + entities;
    } else {/*from  w w  w . j  ava2 s.co m*/
        url += "/?" + entities;
    }

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.socket.timeout", 10000);

    HttpGet getRequest = new HttpGet(url);

    HttpParams params = new BasicHttpParams().setParameter("http.protocol.handle-redirects", false);
    getRequest.setParams(params);
    getRequest.addHeader("accept", "application/sparql-results+xml");
    getRequest.addHeader("accept-encoding", "gzip, deflate");

    try {
        HttpResponse response = httpClient.execute(getRequest);

        // moved permanently
        if (response.getStatusLine().getStatusCode() == 301) {
            Header locationHeader = response.getFirstHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue().split("\\?query")[0];
                logger.debug(endpoint.getEndpointID() + ": SPARQL Endpoint unreachable. Moved permanently to "
                        + redirectLocation);

                endpoint.setSparqlEndpoint(redirectLocation);
                endpointService.updateSPARQLEndpoint(endpoint, redirectLocation);
            }
        }
    } catch (IOException e) {
        // don't react on exception, because this is only a check for HTTP moved endpoints
    }
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;
    Certificate[] sslCertificate;
    HttpHost proxy;/*from  w  w w . jav  a 2  s  . c o  m*/

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        proxy = new HttpHost(proxyAddress, proxyPort, "https");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:net.joala.expression.library.net.UriStatusCodeExpression.java

@Override
@Nonnull// ww w . j  ava2 s.co  m
public Integer get() {
    final String host = uri.getHost();
    checkState(knownHost().matches(host), "Host %s from URI %s is unknown.", host, uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        final HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, (int) timeout.in(TimeUnit.MILLISECONDS));
        HttpConnectionParams.setSoTimeout(httpParams, (int) timeout.in(TimeUnit.MILLISECONDS));
        final HttpUriRequest httpHead = new HttpHead(uri);
        try {
            final HttpResponse response = httpClient.execute(httpHead);
            final HttpEntity httpEntity = response.getEntity();
            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();
            if (httpEntity != null) {
                EntityUtils.consume(httpEntity);
            }
            return statusCode;
        } catch (IOException e) {
            throw new ExpressionEvaluationException(format("Failure reading from URI %s.", uri), e);
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.hubiquitus.twitter4j_1_1.stream.HStatusUpdate.java

/**
 * Used to set proxy params to the DefaultHttpClient
 * @param client//from w w w .  j  a  va  2  s. co m
 */
private void setProxyParams(DefaultHttpClient client) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    log.debug("using a proxy : " + proxyHost + ":" + proxyPort);
}

From source file:org.sociotech.communitymashup.source.mendeley.sdkadaption.AdaptedDocumentServiceImpl.java

protected String callGetForRedirectUrl(String apiUrl) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    try {//from   w  ww .  j a v a2  s  . com
        HttpGet httpget = new HttpGet(apiUrl);
        if (!requestParameters.isEmpty()) {
            HttpParams params = httpget.getParams();
            for (String name : requestParameters.keySet()) {
                params.setParameter(name, requestParameters.get(name));
            }
        }

        for (String headerName : requestHeaders.keySet()) {
            httpget.addHeader(headerName, requestHeaders.get(headerName));
        }

        signRequest(httpget);

        HttpResponse response = httpclient.execute(httpget);

        if (!((response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_TEMP)
                || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_PERM)
                || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_SEE_OTHER))) {
            return null;
        }

        // redirect location is in location header
        Header[] locationHeader = response.getHeaders("location");

        if (locationHeader.length >= 1) {
            return locationHeader[0].getValue();
        }
    } catch (IOException e) {
        throw new MendeleyException(e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }

    return null;
}

From source file:com.google.code.maven.plugin.http.client.Proxy.java

/**
 * prepares the httpclient for using this proxy configuration when opening http connection
 * // w ww  . ja  v a2s .c  om
 * @param httpclient
 */
public void prepare(DefaultHttpClient httpclient) {
    HttpHost proxyHost = new HttpHost(host, port);
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
    if (credentials != null) {
        httpclient.getCredentialsProvider().setCredentials(//
                new AuthScope(host, port), //
                credentials.toUsernamePasswordCredentials());
    }
}