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:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java

@Test
public void testSetParams() {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);
    params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, "pass");
    params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, "user");
    params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345);
    params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345);
    params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345);
    params.set(HttpClientUtil.PROP_USE_RETRY, false);
    DefaultHttpClient client = (DefaultHttpClient) HttpClientUtil.createClient(params);
    try {/*  w ww.j  a  va2 s .com*/
        assertEquals(12345, HttpConnectionParams.getConnectionTimeout(client.getParams()));
        assertEquals(PoolingClientConnectionManager.class, client.getConnectionManager().getClass());
        assertEquals(22345, ((PoolingClientConnectionManager) client.getConnectionManager()).getMaxTotal());
        assertEquals(32345,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getDefaultMaxPerRoute());
        assertEquals(42345, HttpConnectionParams.getSoTimeout(client.getParams()));
        assertEquals(HttpClientUtil.NO_RETRY, client.getHttpRequestRetryHandler());
        assertEquals("pass",
                client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)).getPassword());
        assertEquals("user", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234))
                .getUserPrincipal().getName());
        assertEquals(true, client.getParams().getParameter(ClientPNames.HANDLE_REDIRECTS));
    } finally {
        client.close();
    }
}

From source file:org.opencastproject.workflow.handler.HttpNotificationWorkflowOperationHandler.java

/**
 * Execute the given notification request. If the target is not responding, retry as many time as the maxAttampts
 * parameter with in between each try a sleep time.
 *
 * @param request//w  w w . j  av a2  s .  co m
 *          The request to execute
 * @param maxAttempts
 *          The number of attempts in case of error
 * @param timeout
 *          The wait time in milliseconds at which a connection attempt will throw
 * @return true if the request has been executed successfully
 */
private boolean executeRequest(HttpUriRequest request, int maxAttempts, int timeout, int sleepTime) {

    logger.debug(format("Executing notification request on target %s, %d attemps left", request.getURI(),
            maxAttempts));

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

    HttpResponse response;
    try {
        response = httpClient.execute(request);
    } catch (ClientProtocolException e) {
        logger.error(format("Protocol error during execution of query on target %s: %s", request.getURI(),
                e.getMessage()));
        return false;
    } catch (IOException e) {
        logger.error(format("I/O error during execution of query on target %s: %s", request.getURI(),
                e.getMessage()));
        return false;
    }

    Integer statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == SC_OK || statusCode == SC_NO_CONTENT || statusCode == SC_ACCEPTED) {
        logger.debug(format("Request successfully executed on target %s, status code: %d", request.getURI(),
                statusCode));
        return true;
    } else if (maxAttempts > 1) {
        logger.debug(format("Request failed on target %s, status code: %d, will retry in %d seconds",
                request.getURI(), statusCode, sleepTime / 1000));
        try {
            Thread.sleep(sleepTime);
            return executeRequest(request, --maxAttempts, timeout, sleepTime * SLEEP_SCALE_FACTOR);
        } catch (InterruptedException e) {
            logger.error("Error during sleep time before new notification request try: {}", e.getMessage());
            return false;
        }
    } else {
        logger.warn(format("Request failed on target %s, status code: %d, no more attempt.", request.getURI(),
                statusCode));
        return false;
    }
}

From source file:uk.ac.ebi.phenotype.imaging.springrest.images.dao.ImagesSolrJ.java

public ImagesSolrJ(String solrBaseUrl) throws MalformedURLException {

    // Use system proxy if set
    if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {

        String PROXY_HOST = System.getProperty("http.proxyHost");
        Integer PROXY_PORT = Integer.parseInt(System.getProperty("http.proxyPort"));
        HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT, "http");
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        server = new HttpSolrServer(solrBaseUrl, client);

        log.debug("Proxy Settings: " + System.getProperty("http.proxyHost") + " on port: "
                + System.getProperty("http.proxyPort"));
    } else {/* w ww  .  j a  va  2  s . c om*/
        server = new HttpSolrServer(solrBaseUrl);
    }
}

From source file:messenger.PlurkApi.java

public String login() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }//from w w w  . j a va 2s .  c  om

    HttpGet httpget = new HttpGet(getApiUri("/Users/login?" + "api_key=" + API_KEY + "&" + "username="
            + username + "&" + "password=" + password));
    HttpResponse response = null;
    String responseString = null;
    try {
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cookiestore = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else {
            System.out.println(response.getStatusLine());
            responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}

From source file:org.hk.jt.client.core.Request.java

private HttpResponse execPost() throws URISyntaxException, InvalidKeyException, UnsupportedEncodingException,
        NoSuchAlgorithmException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpPost httpPost = new HttpPost();
    httpPost.setURI(new URI(requestIf.getUrl()));
    httpPost.setHeader("Authorization", createAuthorizationValue());

    if (postParameter != null && !postParameter.isEmpty()) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : postParameter.keySet()) {
            params.add(new BasicNameValuePair(key, postParameter.get(key)));
        }//www.  ja v a  2 s .  co  m
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    }

    if (requestIf.getFiles() != null) {
        final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        List<NameValuePair> fileList = requestIf.getFiles();
        if (fileList != null && !fileList.isEmpty()) {
            for (NameValuePair val : fileList) {
                File file = new File(val.getValue());
                entity.addPart(val.getName(), new FileBody(file, CONTENTTYPE_BINARY));
            }
        }
        httpPost.setEntity(entity);
    }
    httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    return client.execute(httpPost);
}

From source file:com.betaplay.sdk.http.HttpClient.java

private void executeRequest(HttpUriRequest request, String url) {

    DefaultHttpClient client = sslClient(new DefaultHttpClient());
    HttpParams params = client.getParams();

    // timeout 40 sec
    HttpConnectionParams.setConnectionTimeout(params, 40 * 1000);
    HttpConnectionParams.setSoTimeout(params, 40 * 1000);

    HttpResponse httpResponse;//from  w  w w .j  a v  a 2 s.com

    try {
        httpResponse = client.execute(request);
        mResponseCode = httpResponse.getStatusLine().getStatusCode();
        mMessage = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            mResponse = convertStreamToString(instream);

            instream.close();
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

From source file:messenger.PlurkApi.java

public String logout() {
    PlurkApi p = PlurkApi.getInstance();
    if (cookiestore == null)
        p.login();/*w  w  w  .  j a v  a 2 s .  co  m*/
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpclient.setCookieStore(cookiestore);

    HttpResponse response = null;
    String responseString = null;
    try {
        HttpGet httpget = new HttpGet(getApiUri("/Users/logout?" + "api_key=" + API_KEY));
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cookiestore = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else {
            System.out.println(response.getStatusLine());
            responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}

From source file:messenger.PlurkApi.java

public String plurkAdd(String url) {
    PlurkApi p = PlurkApi.getInstance();
    if (cookiestore == null)
        p.login();/* w w w . j ava  2 s . c om*/
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpclient.setCookieStore(cookiestore);

    HttpResponse response = null;
    String responseString = null;
    try {
        String content = URLEncoder.encode(url, "UTF-8");
        HttpGet httpget = new HttpGet(getApiUri("/Timeline/plurkAdd?" + "api_key=" + API_KEY + "&" + "content="
                + content + "&" + "qualifier=" + "says" + "&" + "lang=tr_ch"));
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cookiestore = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else {
            System.out.println(response.getStatusLine());
            responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {//from  w w w . j a  v a 2s.  c om
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:org.transdroid.search.Demonoid.DemonoidAdapter.java

@Override
public List<SearchResult> search(Context context, String query, SortOrder order, int maxResults)
        throws Exception {

    if (query == null) {
        return null;
    }// w  ww. ja v  a  2 s.  c o  m

    this.maxResults = maxResults;

    // Build a search request parameters
    String encodedQuery = "";
    try {
        encodedQuery = URLEncoder.encode(query, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw e;
    }

    final String url = String.format(QUERYURL, encodedQuery,
            (order == SortOrder.BySeeders ? SORT_SEEDS : SORT_COMPOSITE));

    // Start synchronous search

    // Setup request using GET
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);
    // Spoof Firefox user agent to force a result
    httpclient.getParams().setParameter("http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    HttpGet httpget = new HttpGet(url);

    // Make request
    HttpResponse response = httpclient.execute(httpget);

    // Read HTML response
    InputStream instream = response.getEntity().getContent();
    String html = HttpHelper.convertStreamToString(instream);
    instream.close();
    return parseHtml(html);

}