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:eu.dime.userresolver.client.utils.HttpUtils.java

public static DefaultHttpClient createHttpClient() {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if ((proxyHost != null) && (proxyPort != null)) {
        HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }// w w  w.  j  a va  2  s  . co m

    return httpClient;

}

From source file:org.jboss.jdf.stacks.StacksFactory.java

private static void configureProxy(final DefaultHttpClient client, final StacksConfiguration stacksConfig) {
    if (stacksConfig.getProxyHost() != null) {
        final String proxyHost = stacksConfig.getProxyHost();
        final int proxyPort = stacksConfig.getProxyPort();
        final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        final String proxyUsername = stacksConfig.getProxyUser();
        if (proxyUsername != null && !proxyUsername.isEmpty()) {
            final String proxyPassword = stacksConfig.getProxyPassword();
            final AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);//from www .java2  s. c  om
            client.getCredentialsProvider().setCredentials(authScope, credentials);
        }
    }
}

From source file:be.ac.ucl.lfsab1509.llncampus.ExternalAppUtility.java

/**
 * Create a new HTTP client with always the same session of cookies.
 * This can be used for ADE connections for example.
 * //from w  w w  . j a  v  a2  s  .  co  m
 * @return An HttpClient. 
 */
public static synchronized HttpClient getHttpClient() {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    if (cookieStore == null) {
        cookieStore = httpClient.getCookieStore();
    } else {
        httpClient.setCookieStore(cookieStore);
    }
    HttpProtocolParams.setUserAgent(httpClient.getParams(), "Mozilla 5/0");
    return httpClient;
}

From source file:eu.masconsult.bgbanking.banks.sgexpress.SGExpressClient.java

/**
 * Configures the httpClient to connect to the URL provided.
 * /*w w  w  .j a v  a  2s .co  m*/
 * @param authToken
 */
private static DefaultHttpClient getHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    HttpClientParams.setRedirecting(params, false);
    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.addRequestInterceptor(new DumpHeadersRequestInterceptor());
    httpClient.addResponseInterceptor(new DumpHeadersResponseInterceptor());
    httpClient.addResponseInterceptor(new CookieQuotesFixerResponseInterceptor());
    return httpClient;
}

From source file:net.translatewiki.app.TranslateWikiApp.java

public static MWApi createMWApi() {
    DefaultHttpClient client = new DefaultHttpClient();
    // Because WMF servers support only HTTP/1.0. Biggest difference that
    // this makes is support for Chunked Transfer Encoding. 
    // I have this here so if any 1.1 features start being used, it 
    // throws up. 
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    return new MWApi(API_URL, client);
}

From source file:com.github.koraktor.steamcondenser.steam.community.WebApi.java

/**
 * Fetches data from Steam Web API using the specified interface, method
 * and version. Additional parameters are supplied via HTTP GET. Data is
 * returned as a String in the given format.
 *
 * @param apiInterface The Web API interface to call, e.g.
 *                     <code>ISteamUser</code>
 * @param format The format to load from the API ("json", "vdf", or "xml")
 * @param method The Web API method to call, e.g.
 *               <code>GetPlayerSummaries</code>
 * @param params Additional parameters to supply via HTTP GET
 * @param version The API method version to use
 * @return Data is returned as a String in the given format (which may be
 *        "json", "vdf", or "xml")./*  ww  w .  ja  v  a2s  .co m*/
 * @throws WebApiException In case of any request failure
 */
public static String load(String format, String apiInterface, String method, int version,
        Map<String, Object> params) throws WebApiException {
    String protocol = secure ? "https" : "http";
    String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method,
            version);

    if (params == null) {
        params = new HashMap<String, Object>();
    }
    params.put("format", format);
    if (apiKey != null) {
        params.put("key", apiKey);
    }

    boolean first = true;
    for (Map.Entry<String, Object> param : params.entrySet()) {
        if (first) {
            first = false;
        } else {
            url += '&';
        }

        url += String.format("%s=%s", param.getKey(), param.getValue());
    }

    if (LOG.isLoggable(Level.INFO)) {
        String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET");
        LOG.info("Querying Steam Web API: " + debugUrl);
    }

    String data;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);

        Integer statusCode = response.getStatusLine().getStatusCode();
        if (!statusCode.toString().startsWith("20")) {
            if (statusCode == 401) {
                throw new WebApiException(WebApiException.Cause.UNAUTHORIZED);
            }

            throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode,
                    response.getStatusLine().getReasonPhrase());
        }

        data = EntityUtils.toString(response.getEntity());
    } catch (WebApiException e) {
        throw e;
    } catch (Exception e) {
        throw new WebApiException("Could not communicate with the Web API.", e);
    }

    return data;
}

From source file:com.github.koraktor.steamcondenser.community.WebApi.java

/**
 * Fetches data from Steam Web API using the specified interface, method
 * and version. Additional parameters are supplied via HTTP GET. Data is
 * returned as a String in the given format.
 *
 * @param apiInterface The Web API interface to call, e.g.
 *                     <code>ISteamUser</code>
 * @param format The format to load from the API ("json", "vdf", or "xml")
 * @param method The Web API method to call, e.g.
 *               <code>GetPlayerSummaries</code>
 * @param params Additional parameters to supply via HTTP GET
 * @param version The API method version to use
 * @return Data is returned as a String in the given format (which may be
 *        "json", "vdf", or "xml").//w w  w  . jav  a2s . com
 * @throws WebApiException In case of any request failure
 */
public static String load(String format, String apiInterface, String method, int version,
        Map<String, Object> params) throws WebApiException {
    String protocol = secure ? "https" : "http";
    String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method,
            version);

    if (params == null) {
        params = new HashMap<String, Object>();
    }
    params.put("format", format);
    if (apiKey != null) {
        params.put("key", apiKey);
    }

    boolean first = true;
    for (Map.Entry<String, Object> param : params.entrySet()) {
        if (first) {
            first = false;
        } else {
            url += '&';
        }

        url += String.format("%s=%s", param.getKey(), param.getValue());
    }

    if (LOG.isInfoEnabled()) {
        String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET");
        LOG.info("Querying Steam Web API: " + debugUrl);
    }

    String data;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);

        Integer statusCode = response.getStatusLine().getStatusCode();
        if (!statusCode.toString().startsWith("20")) {
            if (statusCode == 401) {
                throw new WebApiException(WebApiException.Cause.UNAUTHORIZED);
            }

            throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode,
                    response.getStatusLine().getReasonPhrase());
        }

        data = EntityUtils.toString(response.getEntity());
    } catch (WebApiException e) {
        throw e;
    } catch (Exception e) {
        throw new WebApiException("Could not communicate with the Web API.", e);
    }

    return data;
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static HttpClient newHttpClient() {
    int timeout = 3 * 60 * 1000;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager mgr = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry());
    httpClient = new DefaultHttpClient(cm, params);

    // how long are we prepared to wait to establish a connection?
    HttpConnectionParams.setConnectionTimeout(params, timeout);

    // how long should the socket wait for data?
    HttpConnectionParams.setSoTimeout(params, timeout);

    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false) {

        @Override/*from w  w  w .  j av a 2 s .c  o m*/
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return super.retryRequest(exception, executionCount, context);
        }

        @Override
        public boolean isRequestSentRetryEnabled() {
            return false;
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            response.removeHeaders("Set-Cookie");

            HttpEntity entity = response.getEntity();
            Header contentEncodingHeader = entity.getContentEncoding();
            if (contentEncodingHeader != null) {
                HeaderElement[] codecs = contentEncodingHeader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }

        }

    });
    return httpClient;
}

From source file:de.onyxbits.raccoon.gplay.PlayManager.java

/**
 * create a proxy client/*from   w ww.ja v a  2s  .  c om*/
 * 
 * @return either a client or null if none is configured
 * @throws KeyManagementException
 * @throws NumberFormatException
 *           if that port could not be parsed.
 * @throws NoSuchAlgorithmException
 */
private static HttpClient createProxyClient(PlayProfile profile)
        throws KeyManagementException, NoSuchAlgorithmException {
    if (profile.getProxyAddress() == null) {
        return null;
    }

    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(30);

    DefaultHttpClient client = new DefaultHttpClient(connManager);
    client.getConnectionManager().getSchemeRegistry().register(Utils.getMockedScheme());
    HttpHost proxy = new HttpHost(profile.getProxyAddress(), profile.getProxyPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (profile.getProxyUser() != null && profile.getProxyPassword() != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(profile.getProxyUser(), profile.getProxyPassword()));
    }
    return client;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.HttpUtils.java

/**
 * @param config Gerrit Server Configuration.
 * @param url URL to get./*from w  w w.  jav  a  2 s.  com*/
 * @return httpresponse.
 * @throws IOException if found.
 */
public static HttpResponse performHTTPGet(IGerritHudsonTriggerConfig config, String url) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) {
        try {
            URL proxyUrl = new URL(config.getGerritProxy());
            HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
        }
    }

    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials());
    HttpResponse execute;
    return httpclient.execute(httpGet);
}