Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager.

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:test.gov.nih.nci.cacoresdk.domain.operations.SpecimenResourceTest.java

public void testPost() throws Exception {

    try {//from  w w  w  .  ja v  a 2 s  .  com
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/Specimen";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(url);
        File myFile = new File("Specimen" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("Specimen" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:test.gov.nih.nci.cacoresdk.domain.operations.ChildTestResourceTest.java

public void testPost() throws Exception {

    try {//from  w  w  w . ja  v  a  2  s .c om
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/ChildTest";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(url);
        File myFile = new File("ChildTest" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("ChildTest" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java

/**
 * Get a user token. Also assigns the token to the inner member (token) of this class.
 *
 * @param username the users username/*from www . j a  va2s  . c o  m*/
 * @param password the users password
 * @return a populated TokenData object or null
 * @throws Exception when there is http problems
 */
String getUserToken(String username, String password) {
    DefaultHttpClient client = getNewClient();
    String tokenFound = null;
    try {
        // Use basicAuth to make the request to the server
        HttpResponse response = HTTPUtils.basicAuthRequest(GET_USER_TOKEN, username, password, client);

        HttpEntity entity = response.getEntity();

        if ((response.getStatusLine().getStatusCode() != 200) || (entity.getContentLength() == 1)) {
            return null;
        }

        // Convert the xml response into an object
        String xml = convertStreamToString(entity.getContent());

        String guid = getTagValue(xml, 0, "guid");

        tokenFound = guid;
    } catch (HttpUtilsException e) {
        throw new RuntimeException("Failed to get token", e);
    } catch (IllegalStateException e) {
        throw new RuntimeException("Failed to get token", e);
    } catch (IOException e) {
        throw new RuntimeException("Failed to get token", e);
    } finally {
        client.getConnectionManager().shutdown();
    }

    return tokenFound;
}

From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Test
public void testBasicAuth() throws Exception {
    URL url = new URL(this.urlStr);

    DefaultHttpClient httpclient = null;

    try {//  w  w w .  jav a 2  s  . co  m
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm());

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:makesense.ara.Collector.java

private void connect() {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {/*w w w . ja v a  2  s  .com*/

        // for the moment, we use AuthScope.ANY and SingleAuth
        // in the future, think about MultiAuth to allow several accounts
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(data.get("login"), data.get("password")));

        HttpGet httpget = new HttpGet(data.get("URL"));

        HttpResponse httpResponse = httpclient.execute(httpget);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            String content;
            BufferedReader br = new BufferedReader(new InputStreamReader(instream));

            // we read as long as we do not ask to stop
            while (!stop) {

                content = br.readLine();
                if (content != null) {

                    System.out.println(content);

                } // if

            } // while

        } // if

    } // try

    catch (IOException ioe) {

        ioe.printStackTrace();

    } // catch

    finally {

        httpclient.getConnectionManager().shutdown();

    } // finally

}

From source file:org.nuxeo.ecm.core.opencmis.impl.NuxeoSessionTestCase.java

@Test
public void testContentStream() throws Exception {
    Document file = (Document) session.getObjectByPath("/testfolder1/testfile1");

    // check ETag header
    if (isAtomPub || isBrowser) {
        RepositoryInfo ri = session.getRepositoryInfo();
        String uri = ri.getThinClientUri() + ri.getId() + "/";
        uri += isAtomPub ? "content?id=" : "root?objectId=";
        uri += file.getId();/*from w  ww .j av  a  2s .  co m*/
        String eTag = file.getPropertyValue("nuxeo:contentStreamDigest");
        String encoding = Base64.encodeBytes(new String(USERNAME + ":" + PASSWORD).getBytes());
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        request.setHeader("Authorization", "Basic " + encoding);
        request.setHeader("If-None-Match", eTag);
        try {
            HttpResponse response = client.execute(request);
            assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    // get stream
    ContentStream cs = file.getContentStream();
    assertNotNull(cs);
    assertEquals("text/plain", cs.getMimeType());
    assertEquals("testfile.txt", cs.getFileName());
    if (!(isAtomPub || isBrowser)) {
        // TODO fix AtomPub/Browser case where the length is unknown (streaming)
        assertEquals(Helper.FILE1_CONTENT.length(), cs.getLength());
    }
    assertEquals(Helper.FILE1_CONTENT, Helper.read(cs.getStream(), "UTF-8"));

    // set stream
    // TODO convenience constructors for ContentStreamImpl
    byte[] streamBytes = STREAM_CONTENT.getBytes("UTF-8");
    ByteArrayInputStream stream = new ByteArrayInputStream(streamBytes);
    cs = new ContentStreamImpl("foo.txt", BigInteger.valueOf(streamBytes.length), "text/plain; charset=UTF-8",
            stream);
    file.setContentStream(cs, true);

    // refetch stream
    file = (Document) session.getObject(file);
    cs = file.getContentStream();
    assertNotNull(cs);
    // AtomPub lowercases charset -> TODO proper mime type comparison
    String mimeType = cs.getMimeType().toLowerCase().replace(" ", "");
    assertEquals("text/plain;charset=utf-8", mimeType);
    // TODO fix AtomPub case where the filename is null
    assertEquals("foo.txt", cs.getFileName());
    if (!(isAtomPub || isBrowser)) {
        // TODO fix AtomPub/Browser case where the length is unknown (streaming)
        assertEquals(streamBytes.length, cs.getLength());
    }
    assertEquals(STREAM_CONTENT, Helper.read(cs.getStream(), "UTF-8"));

    // delete
    file.deleteContentStream();
    file.refresh();
    assertEquals(null, file.getContentStream());
}

From source file:com.mediaportal.ampdroid.api.JsonClient.java

private String executeRequest(HttpUriRequest request, int _timeout, String url) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, _timeout);
    HttpConnectionParams.setSoTimeout(httpParameters, _timeout);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);

    DefaultHttpClient client = new DefaultHttpClient(httpParameters);
    request.setHeader("User-Agent", Constants.USER_AGENT);

    if (mUseAuth) {
        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(mUser, mPass));
        client.setCredentialsProvider(credProvider);
    }/*w ww  .ja v  a  2  s .co  m*/

    HttpResponse httpResponse;

    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();

            return response;
        }

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

From source file:cn.ctyun.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*w w  w. jav a 2  s  .c  o m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:com.abombrecords.amt_unlocker.AMT_Unlocker.java

public static boolean UnlockDoor(String Username, String Password, String DoorPIN) throws Exception {
    boolean bSuccess = false;

    //Log.d(LogTag, "Login");   
    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpPost httpost = new HttpPost("http://acemonstertoys.org/node?destination=node");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("op", "Log in"));
    nvps.add(new BasicNameValuePair("name", Username));
    nvps.add(new BasicNameValuePair("pass", Password));
    nvps.add(new BasicNameValuePair("openid.return_to",
            "http://acemonstertoys.org/openid/authenticate?destination=node"));
    nvps.add(new BasicNameValuePair("form_id", "user_login_block"));
    nvps.add(new BasicNameValuePair("form_build_id", "form-4d6478bc67a79eda5e36c01499ba4c88"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse response = httpclient.execute(httpost);
    HttpEntity entity = response.getEntity();

    //Log.d(LogTag, "Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();//from   w  w w.ja v  a  2 s .c o m
    }

    //Log.d(LogTag, "Post Login cookies:");
    // look for drupal_uid and fail out if it isn't there
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        //Log.d(LogTag, "None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            //Log.d(LogTag, "- " + cookies.get(i).toString());

            if (cookies.get(i).getName().equals("drupal_uid")) {
                bSuccess = true;
            }
        }
    }

    if (bSuccess) {
        HttpPost httpost2 = new HttpPost("http://acemonstertoys.org/membership");

        List<NameValuePair> nvps2 = new ArrayList<NameValuePair>();
        nvps2.add(new BasicNameValuePair("doorcode", DoorPIN));
        nvps2.add(new BasicNameValuePair("forceit", "Open Door"));

        httpost2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));

        response = httpclient.execute(httpost2);
        entity = response.getEntity();

        //Log.d(LogTag, "Unlock form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
    }

    httpclient.getConnectionManager().shutdown();

    return bSuccess;
}

From source file:pt.lunacloud.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config//from w w  w.j a va 2  s .c om
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Form User-Agent information */
    String userAgent = config.getUserAgent();
    if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) {
        userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT;
    }

    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, userAgent);
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new LunacloudClientException("Unable to access default SSL context");
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}