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: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 . ja  v a 2  s.  c  o  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:net.joala.expression.library.net.UriStatusCodeExpression.java

@Override
@Nonnull//from  w w  w  . j  a va 2  s .c o m
public Integer get() {
    final String host = uri.getHost();
    checkState(knownHost().matches(host), "Host %s from URI %s is unknown.", host, uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        final HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, (int) timeout.in(TimeUnit.MILLISECONDS));
        HttpConnectionParams.setSoTimeout(httpParams, (int) timeout.in(TimeUnit.MILLISECONDS));
        final HttpUriRequest httpHead = new HttpHead(uri);
        try {
            final HttpResponse response = httpClient.execute(httpHead);
            final HttpEntity httpEntity = response.getEntity();
            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();
            if (httpEntity != null) {
                EntityUtils.consume(httpEntity);
            }
            return statusCode;
        } catch (IOException e) {
            throw new ExpressionEvaluationException(format("Failure reading from URI %s.", uri), e);
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.jboss.as.testsuite.clustering.web.SimpleWebTestCase.java

@Test
public void test() throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    try {//from  ww w .  j a v a2s . c  o m
        HttpResponse response = client.execute(new HttpGet("http://localhost:8080/distributable/simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(Integer.parseInt(response.getFirstHeader("value").getValue()), 1);
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();

        response = client.execute(new HttpGet("http://localhost:8080/distributable/simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(Integer.parseInt(response.getFirstHeader("value").getValue()), 2);
        // This won't be true unless we have somewhere to which to replicate
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.GTAHttpReader.java

/**
 * extract method in this context does double duty downloading files and
 * unzipping//from www  .jav  a2 s. c om
 */
@Override
public void extract() {
    DefaultHttpClient client = new DefaultHttpClient();
    setCredentials(client);
    //List<String> nodeblinks, inodelinks, rnccnlinks;
    List<String> links = readPage(GTA_URL, client);
    for (String link : links) {
        String pref = link.substring(0, 5);
        if ("NodeB".compareTo(pref) == 0 || "INode".compareTo(pref) == 0 || "RNCCN".compareTo(pref) == 0) {
            for (String filelink : readPage(GTA_URL + link, client)) {
                System.out.println("A" + calendarToString(this.calendar) + "//"
                        + filelink.substring(0, Math.min(filelink.length(), 9)));
                if (("A" + calendarToString(this.calendar))
                        .compareTo(filelink.substring(0, Math.min(filelink.length(), 9))) == 0)
                    fetchLink(GTA_URL + link + filelink, client);
            }
        }
    }
    client.getConnectionManager().shutdown();
}

From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java

public static <SkdsResponse extends BaseResponse> SkdsResponse postJsonRequest(BaseRequest request,
        Class<SkdsResponse> responseClass) throws IllegalStateException, IOException {

    SkdsResponse response = null;/*  ww  w. ja  v a2  s . com*/
    InputStream respIs = null;
    DefaultHttpClient httpclient = null;
    try {
        HttpHost targetHost = new HttpHost(HOST_NAME, PORT, "http");

        httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(USER, PWD));

        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        HttpPost httppost = new HttpPost("/alfresco/service" + request.getJSONUrl() + ".json?requestType=json");

        String req = request.toJSON();
        ByteArrayEntity body = new ByteArrayEntity(req.getBytes());
        httppost.setEntity(body);
        HttpResponse resp = httpclient.execute(targetHost, httppost, localcontext);
        HttpEntity entityResp = resp.getEntity();
        respIs = entityResp.getContent();

        response = TemplateUtils.Encoding.deserializeJSON(responseClass, respIs);

        EntityUtils.consume(entityResp);
        //      } catch(Exception e) {
        //         String message = e.getMessage();
        //         if ( StringUtils.isBlank(message) ) {
        //            message = e.toString();
        //         }
        //         tracer.error(message, e);
        //         throw new RuntimeException(message, e);
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
        IOUtils.closeQuietly(respIs);
    }
    return response;
}

From source file:org.jboss.as.test.clustering.cluster.ejb.stateful.StatefulTimeoutTestCase.java

/**
 * Validates that a @Stateful(passivationCapable=false) bean does not replicate
 *//*from  w w w. j a va  2s  . c o m*/
@Test
public void timeout(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception {

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    URI uri1 = StatefulServlet.createURI(baseURL1, MODULE_NAME, TimeoutIncrementorBean.class.getSimpleName());
    URI uri2 = StatefulServlet.createURI(baseURL2, MODULE_NAME, TimeoutIncrementorBean.class.getSimpleName());

    try {
        assertEquals(1, queryCount(client, uri1));
        assertEquals(2, queryCount(client, uri1));

        // Make sure state replicated correctly
        assertEquals(3, queryCount(client, uri2));
        assertEquals(4, queryCount(client, uri2));

        TimeUnit.SECONDS.sleep(2);

        // SFSB should have timed out
        assertEquals(0, queryCount(client, uri1));
        // Subsequent request will create it again
        assertEquals(1, queryCount(client, uri1));

        TimeUnit.SECONDS.sleep(2);

        // Make sure timeout applies to other node too
        assertEquals(0, queryCount(client, uri2));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:GUI_The_Code_Book.ParserAPIStackEx.java

public ArrayList<URLlist> getStackEx(String word, String web) {
    urlList = new ArrayList<URLlist>();
    word = word.replaceAll(" ", "+");
    String url = "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&accepted=True&title="
            + word + "&site=" + web + "&filter=withbody";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);
    HttpResponse httpResponse;//from ww  w.  j a  v a 2  s  .  co  m
    try {
        httpResponse = httpclient.execute(getRequest);
        HttpEntity entity = httpResponse.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(httpResponse.getStatusLine());
        Header[] headers = httpResponse.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");
        if (entity != null) {
            entity = new GzipDecompressingEntity(entity);
            String jsonStr = EntityUtils.toString(entity);
            //System.out.println(jsonStr);
            parseStackExchange(jsonStr);
        } else {
            System.out.println("NOTHING");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return urlList;
}

From source file:org.jboss.as.test.spec.servlet3.WebSecurityProgrammaticLoginTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from w w w  .  ja v  a 2 s .  c o m*/
        // test hitting programmatic login servlet
        HttpGet httpget = new HttpGet(URL + "?username=" + user + "&password=" + pass);

        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(expectedStatusCode, statusLine.getStatusCode());
        entity.consumeContent();
    } 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:it.openyoureyes.test.OpenCellId.java

public void getCellId(Context context, double latitudine, double longitudine, double distance,
        DefaultHandler dd) throws Exception {

    /*/*from  ww  w  .  ja  va2  s.c o m*/
     * AbstractGeoItem gg=AbstractGeoItem.fromDegrees(latitudine,
     * longitudine); AbstractGeoItem[] bb= gg.boundingCoordinates(1000,
     * 100);
     */
    DefaultHttpClient httpclient = getClient();

    HttpResponse response = null;
    HttpEntity entity = null;

    Location loc1 = new Location("test");
    Location loc2 = new Location("test_");
    AbstractGeoItem.calcDestination(latitudine, longitudine, 225, distance, loc1);
    AbstractGeoItem.calcDestination(latitudine, longitudine, 45, distance, loc2);
    // HttpGet httpost = new
    // HttpGet("http://www.opencellid.org/cell/getInArea?BBOX=14.117,40.781,14.412,40.934&fmt=xml");
    HttpGet httpost = new HttpGet(
            "http://www.opencellid.org/cell/getInArea/?key=622d4c6c01e7ab62187ef7875ce9ea48&BBOX="
                    + loc1.getLatitude() + "," + loc1.getLongitude() + "," + loc2.getLatitude() + ","
                    + loc2.getLongitude() + "&fmt=xml");
    response = httpclient.execute(httpost);

    entity = response.getEntity();
    if (entity != null)
        parseImage(entity, dd);
    response = null;
    entity = null;
    httpclient.getConnectionManager().shutdown();
    httpclient = null;

}

From source file:com.openx.oauth.client.Helper.java

/**
 * Log in to the OpenX OAuth server/* w ww . j  av a 2s.  c o  m*/
 * @return String login string
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
public String doLogin() throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    OpenXRedirectStrategy dsr = new OpenXRedirectStrategy();
    httpclient.setRedirectStrategy(dsr);

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("email", username));
    formparams.add(new BasicNameValuePair("password", password));
    formparams.add(new BasicNameValuePair("oauth_token", token));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    HttpPost httpost = new HttpPost(this.url);
    httpost.setEntity(formEntity);

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

    String result;
    if (response.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(entity);
    } else {
        result = "";
    }

    httpclient.getConnectionManager().shutdown();
    return result;
}