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.haoqee.chatsdk.net.Utility.java

/**
 * Get a HttpClient object which is setting correctly .
 * /*from   w ww  .  ja  v  a2 s  .  c om*/
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static DefaultHttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Utility.SET_SOCKET_TIMEOUT);
    DefaultHttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        // ??PN????
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            // ??????
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                HttpHost proxy = new HttpHost(proxyStr, 80);
                client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
            }
            mCursor.close();
        }
    }
    return client;
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

/**
 * Thread safe client ,since we access the same client across threads
 * @return //w w  w .j ava  2s .  com
 */
public DefaultHttpClient getThreadSafeClient() {
    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);

    DefaultHttpClient aClient = new DefaultHttpClient();
    HttpParams params = aClient.getParams();
    return new DefaultHttpClient(cxMgr, params);
}

From source file:com.su.search.client.solrj.PaHttpSolrServer.java

private DefaultHttpClient createClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ccm = new ThreadSafeClientConnManager(schemeRegistry);
    // Increase default max connection per route to 32
    ccm.setDefaultMaxPerRoute(32);//from ww w.  j av a2 s . co  m
    // Increase max total connection to 128
    ccm.setMaxTotal(128);
    DefaultHttpClient httpClient = new DefaultHttpClient(ccm);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    return httpClient;
}

From source file:com.github.restdriver.clientdriver.integration.BasicAuthTest.java

@Test
public void basicAuthWorks() throws Exception {

    clientDriver.addExpectation(onRequestTo("/").withBasicAuth("Aladdin", "open sesame"),
            giveEmptyResponse().withStatus(418)).anyTimes();

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Aladdin", "open sesame"));

    HttpHost host = new HttpHost("localhost", 12345);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/*w  ww.  j ava 2 s  .  co m*/

    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);

    List<String> authPrefs = new ArrayList<String>();
    authPrefs.add(AuthPolicy.BASIC);
    client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPrefs);

    HttpGet get = new HttpGet(clientDriver.getBaseUrl() + "/");

    HttpResponse response = client.execute(host, get, context);

    assertThat(response.getStatusLine().getStatusCode(), is(418));

}

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

/**
 * Creates a rest client./*from  w  ww .  j  ava2  s  .  c om*/
 * 
 * @param hostname
 *            The host name of the server
 * @param port
 *            The TCP port of the server that should be addressed
 * @param scheme
 *            The used protocol scheme
 * @param versionCode
 *            The version of the app (used for user agent)
 * 
 */
public RestClient(final String hostname, final int port, final String scheme, final int versionCode) {
    final StringBuilder uri = new StringBuilder(scheme);
    uri.append("://");
    uri.append(hostname);
    if (port > 0) {
        uri.append(":");
        uri.append(port);
    }
    mBaseUri = uri.toString();
    mHostName = hostname;

    //TODO Fix SSL problem before exchanging user data
    // workaround for SSL problems, may lower the security level (man-in-the-middle-attack possible)
    // Android does not use the correct SSL certificate for wger.de and throws the exception 
    // javax.net.ssl.SSLException: hostname in certificate didn't match: <wger.de> != <vela.uberspace.de> OR <vela.uberspace.de> OR <uberspace.de> OR <*.vela.uberspace.de>
    // issue is not too serious as no user data is exchanged at the moment
    Log.w(TAG,
            "OpenTraining will accept all SSL-certificates. This issue has to be fixed before exchanging real user data.");
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    ClientConnectionManager mgr = new ThreadSafeClientConnManager(client.getParams(), registry);
    mClient = new DefaultHttpClient(mgr, client.getParams());

    mClient.setRedirectHandler(sRedirectHandler);
    mClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);

    // Set verifier     
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    // set user agent
    USER_AGENT = "opentraining/" + versionCode;
}

From source file:org.ocsinventoryng.android.actions.OCSProtocol.java

public String sendmethod(File pFile, String server, boolean gziped) throws OCSProtocolException {
    OCSLog ocslog = OCSLog.getInstance();
    OCSSettings ocssettings = OCSSettings.getInstance();
    ocslog.debug("Start send method");
    String retour;//  w w w . j a  v  a2s. c o  m

    HttpPost httppost;

    try {
        httppost = new HttpPost(server);
    } catch (IllegalArgumentException e) {
        ocslog.error(e.getMessage());
        throw new OCSProtocolException("Incorect serveur URL");
    }

    File fileToPost;
    if (gziped) {
        ocslog.debug("Start compression");
        fileToPost = ocsfile.getGzipedFile(pFile);
        if (fileToPost == null) {
            throw new OCSProtocolException("Error during temp file creation");
        }
        ocslog.debug("Compression done");
    } else {
        fileToPost = pFile;
    }

    FileEntity fileEntity = new FileEntity(fileToPost, "text/plain; charset=\"UTF-8\"");
    httppost.setEntity(fileEntity);
    httppost.setHeader("User-Agent", http_agent);
    if (gziped) {
        httppost.setHeader("Content-Encoding", "gzip");
    }

    DefaultHttpClient httpClient = getNewHttpClient(OCSSettings.getInstance().isSSLStrict());

    if (ocssettings.isProxy()) {
        ocslog.debug("Use proxy : " + ocssettings.getProxyAdr());
        HttpHost proxy = new HttpHost(ocssettings.getProxyAdr(), ocssettings.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    if (ocssettings.isAuth()) {
        ocslog.debug("Use AUTH : " + ocssettings.getLogin() + "/*****");
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(ocssettings.getLogin(),
                ocssettings.getPasswd());
        ocslog.debug(creds.toString());
        httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    }

    ocslog.debug("Call : " + server);
    HttpResponse localHttpResponse;
    try {
        localHttpResponse = httpClient.execute(httppost);
        ocslog.debug("Message sent");
    } catch (ClientProtocolException e) {
        ocslog.error("ClientProtocolException" + e.getMessage());
        throw new OCSProtocolException(e.getMessage());
    } catch (IOException e) {
        String msg = appCtx.getString(R.string.err_cant_connect) + " " + e.getMessage();
        ocslog.error(msg);
        throw new OCSProtocolException(msg);
    }

    try {
        int httpCode = localHttpResponse.getStatusLine().getStatusCode();
        ocslog.debug("Response status code : " + String.valueOf(httpCode));
        if (httpCode == 200) {
            if (gziped) {
                InputStream is = localHttpResponse.getEntity().getContent();
                GZIPInputStream gzis = new GZIPInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buff = new byte[128];
                int n;
                while ((n = gzis.read(buff, 0, buff.length)) > 0) {
                    baos.write(buff, 0, n);
                }
                retour = baos.toString();
            } else {
                retour = EntityUtils.toString(localHttpResponse.getEntity());
            }
        } else if (httpCode == 400) {
            throw new OCSProtocolException("Error http 400 may be wrong agent version");
        } else {
            ocslog.error("***Server communication error: ");
            throw new OCSProtocolException("Http communication error code " + String.valueOf(httpCode));
        }
        ocslog.debug("Finnish send method");
    } catch (IOException localIOException) {
        String msg = localIOException.getMessage();
        ocslog.error(msg);
        throw new OCSProtocolException(msg);
    }
    return retour;
}