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.soulgalore.crawler.guice.HttpClientProvider.java

/**
 * Get the client.//from w  w w  .j a  v  a2s.co  m
 * 
 * @return the client
 */
public HttpClient get() {
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(nrOfThreads);
    cm.setDefaultMaxPerRoute(maxToRoute);
    final DefaultHttpClient client = HTTPSFaker.getClientThatAllowAnyHTTPS(cm);

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);

    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());

    CookieSpecFactory csf = new CookieSpecFactory() {
        public CookieSpec newInstance(HttpParams params) {
            return new BestMatchSpecWithURLErrorLog();
        }
    };

    client.getCookieSpecs().register("bestmatchwithurl", csf);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "bestmatchwithurl");

    if (!"".equals(proxy)) {
        StringTokenizer token = new StringTokenizer(proxy, ":");

        if (token.countTokens() == 3) {
            String proxyProtocol = token.nextToken();
            String proxyHost = token.nextToken();
            int proxyPort = Integer.parseInt(token.nextToken());

            HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } else
            System.err.println("Invalid proxy configuration: " + proxy);
    }

    if (auths.size() > 0) {

        for (Auth authObject : auths) {
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(authObject.getScope(), authObject.getPort()),
                    new UsernamePasswordCredentials(authObject.getUserName(), authObject.getPassword()));
        }
    }

    return client;
}

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

@Test
public void testLoad() throws Exception {
    DefaultHttpClient httpClient = mock(DefaultHttpClient.class);
    when(httpClient.getParams()).thenReturn(new BasicHttpParams());
    whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(httpClient);

    this.prepareRequest(
            "https://api.steampowered.com/interface/method/v0002/?test=param&format=json&key=0123456789ABCDEF0123456789ABCDEF",
            200, null, "test");

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("test", "param");

    assertThat(WebApi.load("json", "interface", "method", 2, params), is(equalTo("test")));
}

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

@Test
public void testLoadWithoutKey() throws Exception {
    WebApi.setApiKey(null);// ww w. j  av  a 2 s . c o m

    DefaultHttpClient httpClient = mock(DefaultHttpClient.class);
    when(httpClient.getParams()).thenReturn(new BasicHttpParams());
    whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(httpClient);

    this.prepareRequest("https://api.steampowered.com/interface/method/v0002/?test=param&format=json", 200,
            null, "test");

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("test", "param");

    assertThat(WebApi.load("json", "interface", "method", 2, params), is(equalTo("test")));
}

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

@Test
public void testLoadInsecure() throws Exception {
    WebApi.setSecure(false);//from w w w  .  j a v  a 2s .  co  m

    DefaultHttpClient httpClient = mock(DefaultHttpClient.class);
    when(httpClient.getParams()).thenReturn(new BasicHttpParams());
    whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(httpClient);

    this.prepareRequest(
            "http://api.steampowered.com/interface/method/v0002/?test=param&format=json&key=0123456789ABCDEF0123456789ABCDEF",
            200, null, "test");

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("test", "param");

    assertThat(WebApi.load("json", "interface", "method", 2, params), is(equalTo("test")));
}

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

private void prepareRequest(String url, int statusCode, String reason, String content) throws Exception {
    DefaultHttpClient httpClient = mock(DefaultHttpClient.class);
    when(httpClient.getParams()).thenReturn(new BasicHttpParams());
    whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(httpClient);

    HttpGet request = mock(HttpGet.class);
    whenNew(HttpGet.class).withArguments(url).thenReturn(request);

    HttpResponse response = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getReasonPhrase()).thenReturn(reason);
    when(statusLine.getStatusCode()).thenReturn(statusCode);
    when(response.getStatusLine()).thenReturn(statusLine);

    if (content != null) {
        HttpEntity entity = mock(HttpEntity.class);
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(content.getBytes()));
        when(response.getEntity()).thenReturn(entity);
    }// w w w.j av a 2 s.  co  m

    doReturn(response).when(httpClient).execute(request);
    when(httpClient.execute(request)).thenReturn(response);
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnectorTest.java

@Test
public void testProxyReconfigure() {
    final String host = "host";
    final int port = 1234;

    when(proxySettings.isEnabled()).thenReturn(true);
    when(proxySettings.getHostname()).thenReturn(host);
    when(proxySettings.getPort()).thenReturn(port);

    DefaultHttpClient client = (DefaultHttpClient) underTest.client();
    HttpParams params = client.getParams();

    assertThat(ConnRouteParams.getDefaultProxy(params), notNullValue());
    assertThat(params.getParameter(AuthPNames.PROXY_AUTH_PREF), nullValue());

    assertThat(client.getCredentialsProvider().getCredentials(new AuthScope(host, port)), nullValue());

    when(proxySettings.getProxyAuthentication()).thenReturn(proxyAuth);
    when(proxyAuth.getUsername()).thenReturn("user");
    when(proxyAuth.getPassword()).thenReturn("pass");

    final DefaultHttpClient reconfigured = (DefaultHttpClient) underTest.client();
    params = reconfigured.getParams();//from  w  ww. ja v a2 s  . c  o m

    assertThat(reconfigured, equalTo(client));

    assertThat(ConnRouteParams.getDefaultProxy(params), notNullValue());
    assertThat(params.getParameter(AuthPNames.PROXY_AUTH_PREF), notNullValue());

    assertThat(reconfigured.getCredentialsProvider().getCredentials(new AuthScope(host, port)), notNullValue());
}

From source file:com.jelastic.JelasticService.java

private static DefaultHttpClient wrapClient(DefaultHttpClient base) {
    try {//from  www.j a  va  2 s  . c o m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        return null;
    }
}

From source file:swp.bibclient.Network.java

/**
 * Fragt bei einem Server nach den Medien an.
 *
 * @return Die Liste der Medien.//w w w.  j  a v a 2 s . c o  m
 * @throws IOException
 *             Kann geworfen werden bei IO-Problemen.
 */
public final List<Medium> getMediums() throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // Setzen eines ConnectionTimeout von 2 Sekunden:
    HttpParams params = httpClient.getParams();
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    httpClient.setParams(params);

    // Der BibServer sollte lokal laufen, daher zugriff auf Localhost
    // 10.0.2.2 fr den AndroidEmulator.
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(server + mediumpath);
    String text = null;

    Log.i(Network.class.getName(), "Try to get a http connection...");
    HttpResponse response = httpClient.execute(httpGet, localContext);
    HttpEntity entity = response.getEntity();
    text = getASCIIContentFromEntity(entity);
    Log.i(Network.class.getName(), "Create new Gson object");
    Gson gson = new Gson();
    Log.i(Network.class.getName(), "Create listOfTestObject");
    // Wir arbeiten mit einem TypeToken um fr eine generische Liste wieder
    // Objekte zu erhalten.
    Type listOfTestObject = new TypeToken<List<Medium>>() {
    }.getType();

    Log.i(Network.class.getName(), "Convert to a list.");
    /*
     * Hier befindet sich ein unsicherer Cast, da wir nicht wirklich wissen,
     * ob der String, den wir von der Website bekommen, sich wirklich in
     * eine Liste von Bchern umwandeln lsst
     */
    try {
        @SuppressWarnings("unchecked")
        List<Medium> list = Collections.synchronizedList((List<Medium>) gson.fromJson(text, listOfTestObject));
        return list;
    } catch (ClassCastException e) {
        throw new ClientProtocolException("Returned type is not a list of book objects");
    }
}

From source file:net.joala.net.EmbeddedWebservice.java

private DefaultHttpClient getStartupHttpClient() {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,
            (int) SERVER_STARTUP_TIMEOUT.in(TimeUnit.MILLISECONDS));
    HttpConnectionParams.setSoTimeout(httpParams, (int) SERVER_STARTUP_TIMEOUT.in(TimeUnit.MILLISECONDS));
    return httpClient;
}