Example usage for org.apache.http.client HttpClient getConnectionManager

List of usage examples for org.apache.http.client HttpClient getConnectionManager

Introduction

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

Prototype

@Deprecated
ClientConnectionManager getConnectionManager();

Source Link

Document

Obtains the connection manager used by this client.

Usage

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends a {@link MultipartEntity} post with text and image files.
 * //from   w  w  w  .  ja  v  a2s .  c o  m
 * @param url the url to which to POST to.
 * @param user the user or <code>null</code>.
 * @param pwd the password or <code>null</code>.
 * @param stringsMap the {@link HashMap} containing the key and string pairs to send.
 * @param filesMap the {@link HashMap} containing the key and image file paths 
 *                  (jpg, png supported) pairs to send.
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap,
        HashMap<String, File> filesMap)
        throws UnsupportedEncodingException, IOException, ClientProtocolException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(url);

    if (user != null && pwd != null) {
        String ret = getB64Auth(user, pwd);
        httppost.setHeader("Authorization", ret);
    }

    MultipartEntity mpEntity = new MultipartEntity();
    Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet();
    for (Entry<String, String> stringEntry : stringsEntrySet) {
        ContentBody cbProperties = new StringBody(stringEntry.getValue());
        mpEntity.addPart(stringEntry.getKey(), cbProperties);
    }

    Set<Entry<String, File>> filesEntrySet = filesMap.entrySet();
    for (Entry<String, File> filesEntry : filesEntrySet) {
        String propName = filesEntry.getKey();
        File file = filesEntry.getValue();
        if (file.exists()) {
            String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png";
            ContentBody cbFile = new FileBody(file, "image/" + ext);
            mpEntity.addPart(propName, cbFile);
        }
    }

    httppost.setEntity(mpEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:com.jt.https.test.send.java

public static String PostTo(String content) {
    String responseMessage = null;
    String filePath = "";
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }/*  w w  w . ja v  a2s . c  o  m*/
    HttpClient httpclient = new DefaultHttpClient();
    try {
        KeyStore keystore = KeyStore.getInstance("jks");
        KeyStore trustStore = KeyStore.getInstance("jks");

        FileInputStream keystoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\bis-stg-sdb.jks"));
        FileInputStream trustStoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\EXV_GROUP_BIS_IFRONT_JTLZX_100.jks"));
        //FileInputStream keystoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test.jks"));
        //FileInputStream trustStoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test_trust.jks"));
        try {
            keystore.load(keystoreInstream, "123456".toCharArray());
            trustStore.load(trustStoreInstream, "paic1234".toCharArray());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            keystoreInstream.close();
            trustStoreInstream.close();
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.SSL, keystore, "123456",
                trustStore, null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 8107, socketFactory);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpPost post = new HttpPost("https://222.68.184.181:8107");

        StringEntity entity = new StringEntity(content, "text/html", "UTF-8");
        post.setEntity(entity);
        HttpResponse res = httpclient.execute(post);
        HttpEntity resEntity = res.getEntity();
        if (resEntity != null) {
            responseMessage = convertStreamToString(resEntity.getContent());
            System.out.println("???" + content);
            System.out.println("?" + responseMessage);
        }

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return responseMessage;
}

From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java

/**
 * Makes REST API Call for given url parameters and returns the json object
 *
 * @param urlParameters/*from w w  w.j a va 2 s  .com*/
 * @return Json Object in the response body
 */
private JSONObject fetchJson(List<NameValuePair> urlParameters, String azkabanUrl) {
    HttpPost httpPost = new HttpPost(azkabanUrl);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    httpPost.setHeader("Accept", "*/*");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jsonObj = null;
    try {
        SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });

        Scheme scheme = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
        HttpResponse response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new RuntimeException(response.getStatusLine().toString() + "\nStatus code: "
                    + response.getStatusLine().getStatusCode());
        }

        String result = parseContent(response.getEntity().getContent());
        try {
            jsonObj = new JSONObject(result);
            if (jsonObj.has("error")) {
                throw new RuntimeException(jsonObj.get("error").toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return jsonObj;
}

From source file:com.strato.hidrive.api.connection.httpgateway.HTTPGateway.java

/**
 * wrap an httpclient with this stub for prevent ssl unverified exceptions (for testing purposes) 
 *///  w ww  .  j ava 2 s .  c  o  m
public DefaultHttpClient sslStubClient(HttpClient client) {
    try {
        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;
            }
        };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new StubSSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, client.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.apache.solr.client.solrj.impl.BasicHttpSolrServerTest.java

@Test
public void testCompression() throws Exception {
    HttpSolrServer server = new HttpSolrServer(jetty.getBaseUrl().toString() + "/debug/foo");
    SolrQuery q = new SolrQuery("*:*");

    // verify request header gets set
    DebugServlet.clear();/*ww w.  j a va 2 s  . c  o m*/
    try {
        server.query(q);
    } catch (Throwable t) {
    }
    assertNull(DebugServlet.headers.get("Accept-Encoding"));
    server.setAllowCompression(true);
    try {
        server.query(q);
    } catch (Throwable t) {
    }
    assertNotNull(DebugServlet.headers.get("Accept-Encoding"));
    server.setAllowCompression(false);
    try {
        server.query(q);
    } catch (Throwable t) {
    }
    assertNull(DebugServlet.headers.get("Accept-Encoding"));

    // verify server compresses output
    HttpGet get = new HttpGet(jetty.getBaseUrl().toString() + "/collection1" + "/select?q=foo&wt=xml");
    get.setHeader("Accept-Encoding", "gzip");
    HttpClient client = HttpClientUtil.createClient(null);
    HttpEntity entity = null;
    try {
        HttpResponse response = client.execute(get);
        entity = response.getEntity();
        Header ceheader = entity.getContentEncoding();
        assertEquals("gzip", ceheader.getValue());

    } finally {
        if (entity != null) {
            entity.getContent().close();
        }
        client.getConnectionManager().shutdown();
    }

    // verify compressed response can be handled
    server = new HttpSolrServer(jetty.getBaseUrl().toString() + "/collection1");
    server.setAllowCompression(true);
    q = new SolrQuery("foo");
    QueryResponse response = server.query(q);
    assertEquals(0, response.getStatus());
    server.shutdown();
}

From source file:com.sugestio.client.SugestioClient.java

/**
 * Performs a POST request to the given resource. Encodes given JSON object as form data.
 * @param resource// w ww. j  a  va2  s  .c  om
 * @param object the object to submit
 * @return result
 */
private SugestioResult doPost(String resource, Object object) {

    HttpClient httpClient = new DefaultHttpClient();
    JsonObject jsonObject = gson.toJsonTree(object).getAsJsonObject();
    List<NameValuePair> parameters = jsonToNameValuePairs(jsonObject);
    SugestioResult result = new SugestioResult();

    try {

        HttpPost httpPost = new HttpPost(getUri(resource));
        httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        String message = EntityUtils.toString(httpResponse.getEntity());

        result.setCode(httpResponse.getStatusLine().getStatusCode());
        result.setOk(result.getCode() == 202);
        result.setMessage(message);

        httpClient.getConnectionManager().shutdown();

    } catch (Exception e) {

        httpClient.getConnectionManager().shutdown();
        result.setOk(false);
        result.setCode(-1);
        result.setMessage(e.getMessage());
    }

    return result;
}

From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java

@Test
public void testJaxWsBean() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT2 + "/customerservice/customers");
    post.addHeader("Accept", "text/xml");
    String body = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "<soap:Body><GetPerson xmlns=\"http://camel.apache.org/wsdl-first/types\">"
            + "<personId>hello</personId></GetPerson></soap:Body></soap:Envelope>";

    StringEntity entity = new StringEntity(body, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    post.setEntity(entity);/*from  ww w .  j a va 2 s.co  m*/
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(post);
        assertEquals(200, response.getStatusLine().getStatusCode());
        String responseBody = EntityUtils.toString(response.getEntity());
        String correct = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>"
                + "<GetPersonResponse xmlns=\"http://camel.apache.org/wsdl-first/types\">"
                + "<personId>hello</personId><ssn>000-000-0000</ssn><name>Bonjour</name></GetPersonResponse></soap:Body></soap:Envelope>";

        assertEquals("Get a wrong response", correct, responseBody);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.openintents.openpgp.keyserver.HkpKeyServer.java

@Override
public void add(String armoredText) throws AddKeyException {
    HttpClient client = new DefaultHttpClient();
    try {/*  w  ww . j ava 2s  .  c  om*/
        HttpPost post = new HttpPost("http://" + mHost + ":" + mPort + "/pks/add");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("keytext", armoredText));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new AddKeyException();
        }
    } catch (IOException e) {
        e.printStackTrace();
        // nothing to do, better luck on the next keyserver
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.neo4j.server.rest.ConfigureBaseUriDocIT.java

@Test
public void shouldForwardHttpAndHost() throws Exception {
    URI rootUri = functionalTestHelper.baseUri();

    HttpClient httpclient = new DefaultHttpClient();
    try {// ww w.j av a2 s. co m
        HttpGet httpget = new HttpGet(rootUri);

        httpget.setHeader("Accept", "application/json");
        httpget.setHeader("X-Forwarded-Host", "foobar.com");
        httpget.setHeader("X-Forwarded-Proto", "http");

        HttpResponse response = httpclient.execute(httpget);

        String length = response.getHeaders("CONTENT-LENGTH")[0].getValue();
        byte[] data = new byte[Integer.valueOf(length)];
        response.getEntity().getContent().read(data);

        String responseEntityBody = new String(data);

        assertTrue(responseEntityBody.contains("http://foobar.com"));
        assertFalse(responseEntityBody.contains("localhost"));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}