Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

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

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:ui.shared.URLReader.java

private DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
    final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
    try {/*from   www . j a  v  a2s.  c om*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Exception e) {
        throw e;
    }
}

From source file:ilarkesto.net.ApacheHttpDownloader.java

private HttpClient wrapClientForDisabledServerChecking(HttpClient client) {
    try {//  w  w  w.  j  a  va  2s  .co m
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new UnsecureSSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, client.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.groupon.odo.client.Client.java

protected String doPost(String apiUrl, BasicNameValuePair[] data) throws Exception {
    String fullUrl = BASE_URL + apiUrl;
    HttpPost post = new HttpPost(fullUrl);

    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    ArrayList<BasicNameValuePair> dataList = new ArrayList<BasicNameValuePair>();
    if (data != null) {
        dataList.addAll(Arrays.asList(data));
    }//w w w. ja  va2s . c o  m

    // add clientUUID if necessary
    if (_clientId != null) {
        BasicNameValuePair clientPair = new BasicNameValuePair("clientUUID", _clientId);
        dataList.add(clientPair);
    }

    if (dataList.size() > 0) {
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(dataList);
        urlEncodedFormEntity.setContentEncoding(HTTP.UTF_8);
        post.setEntity(urlEncodedFormEntity);
    }

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), _timeout);
    HttpConnectionParams.setSoTimeout(client.getParams(), _timeout);

    HttpResponse response = client.execute(post);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String accumulator = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        accumulator += line;
        accumulator += "\n";
    }
    return accumulator;
}

From source file:com.groupon.odo.client.Client.java

protected String doGet(String apiUrl, BasicNameValuePair[] data) throws Exception {
    String fullUrl = BASE_URL + apiUrl;

    if (data != null) {
        if (data.length > 0) {
            fullUrl += "?";
        }//from ww w.java2s .co m

        for (BasicNameValuePair bnvp : data) {
            fullUrl += bnvp.getName() + "=" + uriEncode(bnvp.getValue()) + "&";
        }
    }

    // add clientUUID if necessary
    if (_clientId != null) {
        if (data == null || data.length == 0) {
            fullUrl += "?";
        }
        fullUrl += "clientUUID=" + _clientId;
    }

    fullUrl += "&profileIdentifier=" + uriEncode(this._profileName);

    HttpGet get = new HttpGet(fullUrl);

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), _timeout);
    HttpConnectionParams.setSoTimeout(client.getParams(), _timeout);

    HttpResponse response = client.execute(get);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String accumulator = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        accumulator += line;
        accumulator += "\n";
    }
    return accumulator;
}

From source file:com.groupon.odo.client.Client.java

protected String doDelete(String apiUrl, BasicNameValuePair[] data) throws Exception {
    String fullUrl = BASE_URL + apiUrl;

    if (data != null) {
        if (data.length > 0) {
            fullUrl += "?";
        }//from   w  ww. j  av a2s  .c  o  m

        for (BasicNameValuePair bnvp : data) {
            fullUrl += bnvp.getName() + "=" + uriEncode(bnvp.getValue()) + "&";
        }
    }

    // add clientUUID if necessary
    if (_clientId != null) {
        if (data == null || data.length == 0) {
            fullUrl += "?";
        }
        fullUrl += "clientUUID=" + _clientId;
    }

    fullUrl += "&profileIdentifier=" + uriEncode(this._profileName);

    HttpDelete get = new HttpDelete(fullUrl);

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), _timeout);
    HttpConnectionParams.setSoTimeout(client.getParams(), _timeout);

    HttpResponse response = client.execute(get);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String accumulator = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        accumulator += line;
        accumulator += "\n";
    }
    return accumulator;
}

From source file:de.madvertise.android.sdk.MadvertiseView.java

/**
 * Starts a background thread to fetch a new ad. Method is called from the
 * refresh timer task// w  w  w. j a  v a  2 s. co  m
 */
private void requestNewAd(final boolean isTimerRequest) {
    if (!mFetchAdsEnabled) {
        MadvertiseUtil.logMessage(null, Log.DEBUG, "Fetching ads is disabled");
        return;
    }

    MadvertiseUtil.logMessage(null, Log.DEBUG, "Trying to fetch a new ad");

    mRequestThread = new Thread(new Runnable() {
        public void run() {
            // read all parameters, that we need for the request
            // get site token from manifest xml file
            String siteToken = MadvertiseUtil.getToken(getContext().getApplicationContext(), mCallbackListener);
            if (siteToken == null) {
                siteToken = "";
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Cannot show ads, since the appID ist null");
            } else {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "appID = " + siteToken);
            }

            // create post request
            HttpPost postRequest = new HttpPost(MadvertiseUtil.MAD_SERVER + "/site/" + siteToken);
            postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            // new ad response version, that supports rich media
            postRequest.addHeader("Accept", "application/vnd.madad+json; version=3");
            List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
            parameterList.add(new BasicNameValuePair("ua", MadvertiseUtil.getUA()));
            parameterList.add(new BasicNameValuePair("app", "true"));
            parameterList.add(new BasicNameValuePair("debug", Boolean.toString(mTestMode)));
            parameterList
                    .add(new BasicNameValuePair("ip", MadvertiseUtil.getLocalIpAddress(mCallbackListener)));
            parameterList.add(new BasicNameValuePair("format", "json"));
            parameterList.add(new BasicNameValuePair("requester", "android_sdk"));
            parameterList.add(new BasicNameValuePair("version", "3.1.3"));
            parameterList.add(new BasicNameValuePair("banner_type", mBannerType));
            parameterList.add(new BasicNameValuePair("deliver_only_text", Boolean.toString(mDeliverOnlyText)));
            if (sAge != null && !sAge.equals("")) {
                parameterList.add(new BasicNameValuePair("age", sAge));
            }

            parameterList.add(new BasicNameValuePair("mraid", Boolean.toString(mIsMraid)));

            if (sGender != null && !sGender.equals("")) {
                parameterList.add(new BasicNameValuePair("gender", sGender));
            }
            final Display display = ((WindowManager) getContext().getApplicationContext()
                    .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            String orientation;
            if (display.getWidth() > display.getHeight()) {
                orientation = "landscape";
            } else {
                orientation = "portrait";
            }

            parameterList.add(new BasicNameValuePair("device_height", Integer.toString(display.getHeight())));
            parameterList.add(new BasicNameValuePair("device_width", Integer.toString(display.getWidth())));

            // When the View is first created, the parent does not exist
            // when this call is made. Hence, we assume that the parent
            // size is equal the screen size for the first call.
            if (mParentWidth == 0 && mParentHeight == 0) {
                mParentWidth = display.getWidth();
                mParentHeight = display.getHeight();
            }

            parameterList.add(new BasicNameValuePair("parent_height", Integer.toString(mParentHeight)));
            parameterList.add(new BasicNameValuePair("parent_width", Integer.toString(mParentWidth)));

            parameterList.add(new BasicNameValuePair("device_orientation", orientation));
            MadvertiseUtil.refreshCoordinates(getContext().getApplicationContext());
            if (MadvertiseUtil.getLocation() != null) {
                parameterList.add(new BasicNameValuePair("lat",
                        Double.toString(MadvertiseUtil.getLocation().getLatitude())));
                parameterList.add(new BasicNameValuePair("lng",
                        Double.toString(MadvertiseUtil.getLocation().getLongitude())));
            }

            parameterList.add(new BasicNameValuePair("app_name",
                    MadvertiseUtil.getApplicationName(getContext().getApplicationContext())));
            parameterList.add(new BasicNameValuePair("app_version",
                    MadvertiseUtil.getApplicationVersion(getContext().getApplicationContext())));

            parameterList.add(new BasicNameValuePair("udid_md5",
                    MadvertiseUtil.getHashedAndroidID(getContext(), MadvertiseUtil.HashType.MD5)));
            parameterList.add(new BasicNameValuePair("udid_sha1",
                    MadvertiseUtil.getHashedAndroidID(getContext(), MadvertiseUtil.HashType.SHA1)));

            parameterList.add(new BasicNameValuePair("mac_md5",
                    MadvertiseUtil.getHashedMacAddress(getContext(), MadvertiseUtil.HashType.MD5)));
            parameterList.add(new BasicNameValuePair("mac_sha1",
                    MadvertiseUtil.getHashedMacAddress(getContext(), MadvertiseUtil.HashType.SHA1)));

            UrlEncodedFormEntity urlEncodedEntity = null;
            try {
                urlEncodedEntity = new UrlEncodedFormEntity(parameterList);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

            postRequest.setEntity(urlEncodedEntity);

            MadvertiseUtil.logMessage(null, Log.DEBUG, "Post request created");
            MadvertiseUtil.logMessage(null, Log.DEBUG, "Uri : " + postRequest.getURI().toASCIIString());
            MadvertiseUtil.logMessage(null, Log.DEBUG,
                    "All headers : " + MadvertiseUtil.getAllHeadersAsString(postRequest.getAllHeaders()));
            MadvertiseUtil.logMessage(null, Log.DEBUG,
                    "All request parameters :" + MadvertiseUtil.printRequestParameters(parameterList));

            synchronized (this) {
                // send blocking request to ad server
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = null;
                InputStream inputStream = null;
                JSONObject json = null;

                try {
                    HttpParams clientParams = httpClient.getParams();
                    HttpConnectionParams.setConnectionTimeout(clientParams, MadvertiseUtil.CONNECTION_TIMEOUT);
                    HttpConnectionParams.setSoTimeout(clientParams, MadvertiseUtil.CONNECTION_TIMEOUT);

                    MadvertiseUtil.logMessage(null, Log.DEBUG, "Sending request");
                    httpResponse = httpClient.execute(postRequest);

                    MadvertiseUtil.logMessage(null, Log.DEBUG,
                            "Response Code => " + httpResponse.getStatusLine().getStatusCode());

                    String message = "";
                    if (httpResponse.getLastHeader("X-Madvertise-Debug") != null) {
                        message = httpResponse.getLastHeader("X-Madvertise-Debug").toString();
                    }

                    if (mTestMode) {
                        MadvertiseUtil.logMessage(null, Log.DEBUG, "Madvertise Debug Response: " + message);
                    }

                    int responseCode = httpResponse.getStatusLine().getStatusCode();

                    HttpEntity entity = httpResponse.getEntity();

                    if (responseCode == 200 && entity != null) {
                        inputStream = entity.getContent();
                        String resultString = MadvertiseUtil.convertStreamToString(inputStream);
                        MadvertiseUtil.logMessage(null, Log.DEBUG, "Response => " + resultString);
                        json = new JSONObject(resultString);

                        // create ad
                        mCurrentAd = new MadvertiseAd(getContext().getApplicationContext(), json,
                                mCallbackListener);

                        calculateBannerDimensions();

                        mHandler.post(mUpdateResults);
                    } else {
                        if (mCallbackListener != null) {
                            mCallbackListener.onIllegalHttpStatusCode(responseCode, message);
                        }
                    }
                } catch (ClientProtocolException e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG, "Error in HTTP request / protocol", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } catch (IOException e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG,
                            "Could not receive a http response on an ad request", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } catch (JSONException e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG, "Could not parse json object", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } catch (Exception e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG,
                            "Could not receive a http response on an ad request", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            if (mCallbackListener != null) {
                                mCallbackListener.onError(e);
                            }
                        }
                    }
                }
            }
        }
    }, "MadvertiseRequestThread");
    mRequestThread.start();
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientFactoryImplTest.java

@Test
@Ignore("DefaultHttpClient is not in use anymore")
public void createdInstanceConfigurationTest() {
    setParameters();/*from w w  w.j  a v  a 2s.c om*/
    try {
        testSubject = new HttpClientFactoryImpl(Providers.of(systemStatus),
                Providers.of(globalRemoteStorageContext), eventBus, jmxInstaller, null);

        // Note: explicitly created instance (like in case of proxies), it does pool and
        // returns customized client

        // we will reuse the "global" one, but this case is treated differently anyway by factory
        final HttpClient client = testSubject
                .create(new RemoteStorageContextCustomizer(globalRemoteStorageContext));
        // shared client does reuse connections (does pool)
        Assert.assertTrue(((DefaultHttpClient) client)
                .getConnectionReuseStrategy() instanceof DefaultConnectionReuseStrategy);
        Assert.assertTrue(
                ((DefaultHttpClient) client).getConnectionManager() instanceof PoolingClientConnectionManager);

        // check is all set as needed: retries
        Assert.assertTrue(((DefaultHttpClient) client)
                .getHttpRequestRetryHandler() instanceof StandardHttpRequestRetryHandler);
        Assert.assertEquals(globalRemoteStorageContext.getRemoteConnectionSettings().getRetrievalRetryCount(),
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .getRetryCount());
        Assert.assertEquals(false,
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .isRequestSentRetryEnabled());

        // check is all set as needed: everything else
        Assert.assertEquals(1234L, client.getParams().getLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 0));
        Assert.assertEquals(1234,
                client.getParams().getIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 0));
        Assert.assertEquals(1234, client.getParams().getIntParameter(HttpConnectionParams.SO_TIMEOUT, 0));
        final PoolingClientConnectionManager realConnMgr = (PoolingClientConnectionManager) client
                .getConnectionManager();
        Assert.assertEquals(1234, realConnMgr.getMaxTotal());
        Assert.assertEquals(1234, realConnMgr.getDefaultMaxPerRoute());
        client.getConnectionManager().shutdown();
    } finally {
        testSubject.shutdown();
        unsetParameters();
    }
}

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderImplTest.java

@Test
@Ignore("DefaultHttpClient is not in use anymore")
public void createdInstanceConfigurationTest() {
    setParameters();/*from w  ww.  j  a va  2 s. co m*/
    try {
        testSubject = new Hc4ProviderImpl(applicationConfiguration, userAgentBuilder, eventBus, jmxInstaller,
                null);

        // Note: explicitly created instance (like in case of proxies), it does pool and
        // returns customized client

        // we will reuse the "global" one, but this case is treated differently anyway by Hc4Provider
        final HttpClient client = testSubject
                .createHttpClient(applicationConfiguration.getGlobalRemoteStorageContext());
        // shared client does reuse connections (does pool)
        Assert.assertTrue(((DefaultHttpClient) client)
                .getConnectionReuseStrategy() instanceof DefaultConnectionReuseStrategy);
        Assert.assertTrue(
                ((DefaultHttpClient) client).getConnectionManager() instanceof PoolingClientConnectionManager);

        // check is all set as needed: retries
        Assert.assertTrue(((DefaultHttpClient) client)
                .getHttpRequestRetryHandler() instanceof StandardHttpRequestRetryHandler);
        Assert.assertEquals(globalRemoteStorageContext.getRemoteConnectionSettings().getRetrievalRetryCount(),
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .getRetryCount());
        Assert.assertEquals(false,
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .isRequestSentRetryEnabled());

        // check is all set as needed: everything else
        Assert.assertEquals(1234L, client.getParams().getLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 0));
        Assert.assertEquals(1234,
                client.getParams().getIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 0));
        Assert.assertEquals(1234, client.getParams().getIntParameter(HttpConnectionParams.SO_TIMEOUT, 0));
        final PoolingClientConnectionManager realConnMgr = (PoolingClientConnectionManager) client
                .getConnectionManager();
        Assert.assertEquals(1234, realConnMgr.getMaxTotal());
        Assert.assertEquals(1234, realConnMgr.getDefaultMaxPerRoute());
        client.getConnectionManager().shutdown();
    } finally {
        testSubject.shutdown();
        unsetParameters();
    }
}

From source file:cl.nic.dte.net.ConexionSii.java

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII,
        String token, String urlEnvio, String hostEnvio)
        throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(urlEnvio);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2)));
    reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length())));
    reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2)));
    reqEntity.addPart("dvCompany",
            new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length())));

    FileBody bin = new FileBody(archivoEnviarSII);
    reqEntity.addPart("archivo", bin);

    httppost.setEntity(reqEntity);//from   w w w .j  a va 2 s . c o m

    BasicClientCookie cookie = new BasicClientCookie("TOKEN", token);
    cookie.setPath("/");
    cookie.setDomain(hostEnvio);
    cookie.setSecure(true);
    cookie.setVersion(1);

    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);

    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));

    HttpResponse response = httpclient.execute(httppost, localContext);

    HttpEntity resEntity = response.getEntity();

    RECEPCIONDTEDocument resp = null;

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();
    opts.setLoadSubstituteNamespaces(namespaces);

    resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts);

    return resp;
}