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.safegees.safegees.util.HttpUrlConnection.java

public String performGetCall(String requestURL, HashMap<String, String> postDataParams,
        String userCredentials) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    final HttpParams httpConnParams = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpConnParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpConnParams, READ_TIMEOUT);
    HttpGet httpGet = new HttpGet(requestURL);
    //Add the auth header
    if (userCredentials != null)
        httpGet.addHeader("auth", userCredentials);
    HttpResponse response = null;//from ww  w  .  j ava2 s .com
    String responseStr = null;
    try {
        response = httpclient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == 200
                || (statusLine.getStatusCode() > 200 && statusLine.getStatusCode() < 300)) {
            responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
        } else {
            Log.e("GET ERROR", response.getStatusLine().toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return responseStr;

}

From source file:com.demo.wtm.service.RestService.java

private void executeRequest(HttpUriRequest request, String url) {

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

    // Setting 30 second timeouts
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
    HttpConnectionParams.setSoTimeout(params, 30 * 1000);

    HttpResponse httpResponse;/*from  w  w  w.j a v a 2s.  co m*/

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

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

            // Closing the input stream will trigger connection release
            instream.close();
        }

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

From source file:de.taxilof.UulmLoginAgent.java

/**
 * perform the Login & necessary Checks
 *//*from  ww  w .  j  a v a  2  s  . c o  m*/
public void login() {
    // setting up my http client
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Linux; U; Android; uulmLogin " + context.getString(R.string.app_version) + ")");
    // disable redirects in client, used from isLoggedIn method
    client.setRedirectHandler(new RedirectHandler() {
        public URI getLocationURI(HttpResponse arg0, HttpContext arg1) throws ProtocolException {
            return null;
        }

        public boolean isRedirectRequested(HttpResponse arg0, HttpContext arg1) {
            return false;
        }
    });

    // get IP
    String ipAddress = getIp();
    if (ipAddress == null) {
        Log.d("uulmLogin", "Could not get IP Address, aborting.");
        return;
    }
    Log.d("uulmLogin", "Got IP: " + ipAddress + ", continuing.");

    // check if IP prefix is wrong
    if (!(ipAddress.startsWith(context.getString(R.string.ip_prefix)))) {
        Log.d("uulmLogin", "Wrong IP Prefix.");
        return;
    }

    // check the SSID
    String ssid = getSsid();
    if (!(context.getString(R.string.ssid).equals(ssid))) {
        Log.d("uulmLogin", "Wrong SSID, aborting.");
        return;
    }

    // check if we are already logged in
    if (isLoggedIn(client, 5)) {
        Log.d("uulmLogin", "Already logged in, aborting.");
        return;
    }

    // try to login via GET Request
    try {
        // login
        HttpGet get = new HttpGet(String.format("%s?username=%s&password=%s&login=Anmelden",
                context.getString(R.string.capo_uri), username, URLEncoder.encode(password)));
        @SuppressWarnings("unused")
        HttpResponse response = client.execute(get);
        Log.d("uulmLogin", "Login done, HttpResponse:" + HttpHelper.request(response));
    } catch (SSLException ex) {
        Log.w("uulmLogin", "SSL Error while sending Login Request: " + ex.toString());
        if (notifyFailure)
            notify("Login to Welcome failed", "SSL Error: could not verify Host", true);
        return;
    } catch (Exception e) {
        Log.w("uulmLogin", "Error while sending Login Request: " + e.toString());
        if (notifyFailure)
            notify("Login to Welcome failed", "Error while sending Login Request.", true);
        return;
    }

    // should be logged in now, but we check it now, just to be sure
    if (isLoggedIn(client, 2)) {
        if (notifySuccess)
            notify("Login to welcome successful.", "Your IP: " + ipAddress, false);
        Log.d("uulmLogin", "Login successful.");
    } else {
        if (notifyFailure)
            notify("Login to welcome failed.", "Maybe wrong Username/Password?", true);
        Log.w("uulmLogin", "Login failed, wrong user/pass?");
    }
}

From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java

@Test
public void testCookieForStateFullClient() throws Exception {
    setAnonymousAccess(false);/*w  ww . j  a v  a 2s  .  c  om*/

    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";
    URI nexusBaseURI = new URI(url);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0");
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // stateful clients must login first, since other rest urls create no sessions
    String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login";
    assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200));

    // after login check content but make sure only cookie is used
    httpClient.getCredentialsProvider().clear();
    HttpGet getMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200));
    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    assertThat("Session Cookie not set", sessionCookie, notNullValue());
    httpClient.getCookieStore().clear(); // remove cookies

    // do not set the cookie, expect failure
    HttpGet failedGetMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401));

    // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail
    // with a 401
    httpClient.getCookieStore().addCookie(sessionCookie);
    getMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200));
}

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

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

    when(proxySettings.isEnabled()).thenReturn(true);
    when(proxySettings.getHostname()).thenReturn(host);
    when(proxySettings.getPort()).thenReturn(port);
    when(proxySettings.getNonProxyHosts()).thenReturn(Sets.newHashSet(".*"));

    final DefaultHttpClient client = (DefaultHttpClient) underTest.client();
    assertThat(ConnRouteParams.getDefaultProxy(client.getParams()), notNullValue());

    final HttpRoutePlanner planner = client.getRoutePlanner();
    final HttpRequest request = mock(HttpRequest.class);
    when(request.getParams()).thenReturn(mock(HttpParams.class));

    planner.determineRoute(new HttpHost("host"), request, mock(HttpContext.class));

    ArgumentCaptor<HttpParams> captor = ArgumentCaptor.forClass(HttpParams.class);

    verify(request).setParams(captor.capture());
    assertThat(ConnRouteParams.getDefaultProxy(captor.getValue()), nullValue());
}

From source file:cloudMe.CloudMeAPI.java

private DefaultHttpClient getConnection() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), USER_AGENT_INFO);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, 80, "os@xcerion.com", "Digest"),
            new UsernamePasswordCredentials(userName, pass)); // Encrypts password & username
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                if (creds != null && scheme != null) {
                    authState.setAuthScheme(scheme);
                    authState.setCredentials(creds);
                } else {
                    scheme = authState.getAuthScheme();
                }//  w w w  .ja v  a 2s.  co m
            }
        }
    };
    httpClient.addRequestInterceptor(preemptiveAuth, 0);
    return httpClient;

}

From source file:net.bither.http.BaseHttpResponse.java

private DefaultHttpClient getThreadSafeHttpClient() {
    if (getHttpType() == HttpType.BitherApi) {
        PersistentCookieStore persistentCookieStore = PersistentCookieStore.getInstance();
        if (persistentCookieStore.getCookies() == null || persistentCookieStore.getCookies().size() == 0) {
            CookieFactory.initCookie();//from w  w  w.j  a  v  a  2  s.  co  m
        }
    }
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager mgr = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HttpSetting.HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HttpSetting.HTTP_SO_TIMEOUT);
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
            params);
    setCookieStore(httpClient);
    return httpClient;
}

From source file:jp.takuo.android.mmsreq.Request.java

protected HttpResponse requestHttp() throws ClientProtocolException, IOException {
    HttpGet reqGet = new HttpGet(REQUEST_URL);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    Log.d(LOG_TAG, "Proxy: " + mProxyHost + ":" + PROXY_PORT);
    ConnRouteParams.setDefaultProxy(params, new HttpHost(mProxyHost, PROXY_PORT));
    Log.d(LOG_TAG, "UserAgent: " + mUserAgent);
    HttpProtocolParams.setUserAgent(params, mUserAgent);
    reqGet.setParams(params);// ww w  .  ja  va 2 s  . com
    Log.d(LOG_TAG, "HTTP Get: " + REQUEST_URL);
    return (HttpResponse) client.execute(reqGet);
}

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

private HttpResponse execGet() throws URISyntaxException, UnsupportedEncodingException, InvalidKeyException,
        IOException, NoSuchAlgorithmException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpGet httpGet = new HttpGet();
    if (postParameter != null && !postParameter.isEmpty()) {
        httpGet.setURI(new URI(requestIf.getUrl() + "?" + getRequestParam()));
    } else {/*from  w w w .j  a  va 2s  .c  o  m*/
        httpGet.setURI(new URI(requestIf.getUrl()));
    }
    httpGet.setHeader("Authorization", createAuthorizationValue());
    return client.execute(httpGet);
}

From source file:org.safegees.safegees.util.HttpUrlConnection.java

public String performPostCall(String requestURL, HashMap<String, String> postDataParams,
        String userCredentials) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    final HttpParams httpConnParams = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpConnParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpConnParams, READ_TIMEOUT);
    HttpPost httpPost = new HttpPost(requestURL);

    try {//from   w ww .jav a 2  s .  co m
        String postDataParamsString = getDataString(postDataParams);
        httpPost.setEntity(new StringEntity(postDataParamsString));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //Add the auth header
        if (userCredentials != null)
            httpPost.addHeader(KEY_HEADER_AUTHORIZED, userCredentials);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    HttpResponse response = null;
    String responseStr = null;
    try {
        response = httpclient.execute(httpPost);
        if (response != null) {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 201
                    || statusLine.getStatusCode() == 204) {
                //responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
                responseStr = statusLine.getReasonPhrase();
            } else {
                Log.e("POST ERROR", response.getStatusLine().toString());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return responseStr;

}