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:de.felixschulze.acra.JsonSender.java

private void sendHttpPost(String data, URL url, String login, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*w w  w  . j  a v a  2 s .  co  m*/
        HttpPost httPost = new HttpPost(url.toString());

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("json", data));

        httPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

        HttpResponse httpResponse = httpClient.execute(httPost);

        Log.d(LOG_TAG, "Server Status: " + httpResponse.getStatusLine());
        Log.d(LOG_TAG, "Server Response: " + EntityUtils.toString(httpResponse.getEntity()));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.pm.myshop.controller.CardController.java

@RequestMapping(value = "/validatecard", method = RequestMethod.GET)
public @ResponseBody String authenticateCard(@RequestParam("cardNo") String cardNo,
        @RequestParam("balance") double balance, @RequestParam("cvv") String cvv) throws IOException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    String encCard = encryptCardNumber(cardNo);

    HttpGet getRequest = new HttpGet("http://localhost:8080/Team4_CardValidator/validate?cardNo=" + encCard
            + "&balance=" + balance + "&cvv=" + cvv);

    getRequest.addHeader(//from  www  .java  2 s  .  c  om
            BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"), "UTF-8", false));

    HttpResponse response = httpClient.execute(getRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        session.setAttribute("cardvalidation", "fail");
        return "fail";
    }

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

    while ((output = br.readLine()) != null) {
        session.setAttribute("cardvalidation", output);
        return output;
    }

    httpClient.getConnectionManager().shutdown();

    session.setAttribute("cardvalidation", "fail");
    return "fail";
}

From source file:BusinessLogic.Controller.RestController.java

public List<Plan> getPlans() throws Exception {
    StringBuilder responseS = new StringBuilder();
    try {//  ww  w . java  2 s. co m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("http://localhost:8080/JoyCenter/resources/plans");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IOException e) {
    }

    Gson gson = new Gson();
    List<Plan> planes = gson.fromJson(responseS.toString(), new TypeToken<List<Plan>>() {
    }.getType());

    return planes;

}

From source file:BusinessLogic.Controller.RestController.java

public List<Viaje> getViajes() throws Exception {
    StringBuilder responseS = new StringBuilder();
    try {/*from ww  w . j  a  v  a  2  s.c o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("http://192.168.162.167/Terminal/resources/viajes/");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IOException e) {
    }
    Gson gson = new Gson();
    List<Viaje> viajes = gson.fromJson(responseS.toString(), new TypeToken<List<Viaje>>() {
    }.getType());
    return viajes;
}

From source file:BusinessLogic.Controller.RestController.java

public Plan getPlan(int planId) throws Exception {
    StringBuilder responseS = new StringBuilder();
    try {/*ww w .  j a  va  2  s  .  c o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("http://localhost/JoyCenter/resources/plans/" + planId);
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IOException e) {
    }

    //Receive response, parse to POJO array.
    Gson gson = new Gson();
    return gson.fromJson(responseS.toString(), Plan.class);
}

From source file:BusinessLogic.Controller.RestController.java

public List<Hotel> getHotels() throws Exception {
    StringBuilder responseS = new StringBuilder();

    try {/*from   www  .j ava  2  s . c o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpGet getRequest = new HttpGet("http://192.168.162.121/Hoex/hoexAPI/hoteles");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

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

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

        httpClient.getConnectionManager().shutdown();

    } catch (IOException e) {
    }

    Gson gson = new Gson();
    List<Hotel> hoteles = gson.fromJson(responseS.toString(), new TypeToken<List<Hotel>>() {
    }.getType());

    return hoteles;

}

From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java

/**
 * {@inheritDoc}//from   ww w .jav  a  2  s .c om
 */
@Override
public <MODEL extends Model> ConnectorResponse execute(Query<MODEL> query) {
    DefaultHttpClient client = createClient();
    HttpGet get = createGetMethod(query);
    try {
        HttpResponse response;
        if (localContext != null) {
            log.debug(
                    "Executing the query: " + query.getUrl() + " using the localContext with the credentials");
            response = client.execute(get, localContext);
        } else {
            log.debug("Executing the query: " + query.getUrl());
            response = client.execute(get);
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return getConnectorResponseFromEntity(response);
        }
    } catch (IOException e) {
        log.error("Failed to execute the query: " + query.getUrl(), e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return null;
}

From source file:org.codegist.crest.io.http.HttpClientFactoryTest.java

@Test
public void createWithMoreThanOneShouldCreateDefaultHttpClientWithConnectionManagerSetup() throws Exception {
    DefaultHttpClient expected = mock(DefaultHttpClient.class);
    ProxySelectorRoutePlanner planner = mock(ProxySelectorRoutePlanner.class);
    ClientConnectionManager clientConnectionManager = mock(ClientConnectionManager.class);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    ProxySelector proxySelector = mock(ProxySelector.class);
    BasicHttpParams httpParams = mock(BasicHttpParams.class);
    ConnPerRouteBean routeBean = mock(ConnPerRouteBean.class);
    PlainSocketFactory plainSocketFactory = mock(PlainSocketFactory.class);
    SSLSocketFactory sslSocketFactory = mock(SSLSocketFactory.class);
    Scheme plainScheme = new Scheme("http", plainSocketFactory, 80);
    Scheme sslScheme = new Scheme("https", sslSocketFactory, 443);
    ThreadSafeClientConnManager threadSafeClientConnManager = mock(ThreadSafeClientConnManager.class);

    when(expected.getConnectionManager()).thenReturn(clientConnectionManager);
    when(clientConnectionManager.getSchemeRegistry()).thenReturn(schemeRegistry);

    mockStatic(ProxySelector.class);
    when(ProxySelector.getDefault()).thenReturn(proxySelector);

    mockStatic(PlainSocketFactory.class);
    when(PlainSocketFactory.getSocketFactory()).thenReturn(plainSocketFactory);

    mockStatic(SSLSocketFactory.class);
    when(SSLSocketFactory.getSocketFactory()).thenReturn(sslSocketFactory);

    whenNew(SchemeRegistry.class).withNoArguments().thenReturn(schemeRegistry);
    whenNew(Scheme.class).withArguments("http", plainSocketFactory, 80).thenReturn(plainScheme);
    whenNew(Scheme.class).withArguments("https", sslSocketFactory, 443).thenReturn(sslScheme);
    whenNew(ThreadSafeClientConnManager.class).withArguments(httpParams, schemeRegistry)
            .thenReturn(threadSafeClientConnManager);
    whenNew(ConnPerRouteBean.class).withArguments(2).thenReturn(routeBean);
    whenNew(BasicHttpParams.class).withNoArguments().thenReturn(httpParams);
    whenNew(DefaultHttpClient.class).withArguments(threadSafeClientConnManager, httpParams)
            .thenReturn(expected);/*from w  ww.j  a  v a  2s.  com*/
    whenNew(ProxySelectorRoutePlanner.class).withArguments(schemeRegistry, proxySelector).thenReturn(planner);

    when(crestConfig.getConcurrencyLevel()).thenReturn(2);
    HttpClient actual = HttpClientFactory.create(crestConfig, getClass());
    assertSame(expected, actual);

    verify(expected).setRoutePlanner(planner);
    verify(httpParams).setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    verify(httpParams).setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, routeBean);
    verify(httpParams).setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 2);
    assertSame(plainScheme, schemeRegistry.getScheme("http"));
    assertSame(sslScheme, schemeRegistry.getScheme("https"));
}

From source file:com.pm.myshop.controller.OrderController.java

public String financeDivide(String particular, double amount, String deductFrom, String depositeTo)
        throws IOException {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet("http://localhost:8080/Team4_MyFinance/add?particular=" + particular
            + "&amount=" + amount + "&deductFrom=" + deductFrom + "&depositeTo=" + depositeTo);

    getRequest.addHeader(//from   w  w  w . j a v a  2 s  .  co m
            BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"), "UTF-8", false));

    HttpResponse response = httpClient.execute(getRequest);

    if (response.getStatusLine().getStatusCode() != 200) {

        return "fail";
    }

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

    while ((output = br.readLine()) != null) {
        return output;
    }

    httpClient.getConnectionManager().shutdown();

    return "fail";
}

From source file:de.uzk.hki.da.repository.ElasticsearchMetadataIndex.java

@Override
public void deleteFromIndex(String indexName, String objectID) throws MetadataIndexException {
    logger.debug("Delete object " + objectID + " from index " + indexName + "...");
    try {//from   ww w. ja v a  2 s.  c  o  m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpDelete deleteRequest = new HttpDelete("http://localhost:9200/" + indexName + "/" + C.ORE_AGGREGATION
                + "/_query?q=_id:" + objectID + "" + "*");
        HttpResponse response = httpClient.execute(deleteRequest);

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        String output;
        logger.debug("Output from Server .... \n");
        while ((output = new BufferedReader(new InputStreamReader((response.getEntity().getContent())))
                .readLine()) != null) {
            logger.debug(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
    }
}