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:com.foundationdb.http.HttpMonitorVerifyIT.java

@Test
public void runTest() throws Exception {
    MonitorService monitor = monitorService();

    HttpClient client = new DefaultHttpClient();
    openRestURL(client, "user1:password", httpConductor().getPort(), "/version");

    assertEquals(monitor.getSessionMonitors().size(), 1);

    client.getConnectionManager().shutdown();
}

From source file:org.apache.camel.component.restlet.RestletTestSupport.java

public HttpResponse doExecute(HttpUriRequest method) throws Exception {
    HttpClient client = new DefaultHttpClient();
    try {/*from   ww  w.j  a  v a  2s .c o  m*/
        HttpResponse response = client.execute(method);
        response.setEntity(new BufferedHttpEntity(response.getEntity()));
        return response;
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.imaginea.betterdocs.BetterDocsAction.java

private static String getESResultJson(String esQueryJson, String url) {
    StringBuilder stringBuilder = new StringBuilder();
    try {//  ww  w .ja  v a  2 s. co m
        HttpClient httpClient = new DefaultHttpClient();
        String encodedJson = URLEncoder.encode(esQueryJson, UTF_8);
        String esGetURL = url + encodedJson;

        HttpGet getRequest = new HttpGet(esGetURL);
        getRequest.setHeader(USER_AGENT, IDEA_PLUGIN);

        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(FAILED_HTTP_ERROR_CODE + url + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        while ((output = br.readLine()) != null) {
            stringBuilder.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return EMPTY_ES_URL;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return EMPTY_ES_URL;
    } catch (IOException e) {
        e.printStackTrace();
        return EMPTY_ES_URL;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return EMPTY_ES_URL;
    }
    return stringBuilder.toString();
}

From source file:sit.web.client.HttpHelper.java

public static void apacheDownload(String downloadUrl, File targetFile) throws IOException {

    URL url = new URL(downloadUrl);

    HttpClient httpclient;
    if (isHTTPS(downloadUrl)) {
        httpclient = HTTPTrustHelper.getNewHttpClient(Charset.defaultCharset(),
                (url.getPort() != -1) ? url.getPort() : url.getDefaultPort());
    } else {// w ww .  ja v  a 2  s  .c  o m
        httpclient = new DefaultHttpClient();
    }

    HttpGet request = new HttpGet(downloadUrl);
    HttpResponse response = httpclient.execute(request);

    InputStream is = response.getEntity().getContent();
    FileOutputStream writer = new FileOutputStream(targetFile);

    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = 0;
        while ((bytesRead = is.read(buffer, 0, buffer.length)) >= 0) {
            writer.write(buffer, 0, bytesRead);
        }
    } finally {
        writer.close();
        is.close();
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static byte[] readFileFromPOST(String sourceUrl, Map<String, String> reqParams) throws IOException {
    HttpClient httpClient = null;
    try {/*from   www  .  ja  v  a 2s . c om*/
        httpClient = getDefaultHttpClient();
        HttpPost httpRequest = new HttpPost(sourceUrl);
        if (null != reqParams && reqParams.size() > 0) {
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            for (String param : reqParams.keySet()) {
                paramList.add(new BasicNameValuePair(param, reqParams.get(param)));
            }
            StringEntity reqEntity = new StringEntity(URLEncodedUtils.format(paramList, "UTF-8"), "UTF-8");
            httpRequest.setEntity(reqEntity);
        }

        HttpResponse response = httpClient.execute(httpRequest);

        return readResponseContent(response);
    } finally {
        if (null != httpClient)
            httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.cm.podd.report.util.RequestDataUtil.java

public static ResponseObject get(String path, String query, String token) {
    JSONObject jsonObj = null;/*from   w  w  w  .  ja v a2s. c o  m*/
    String rawData = null;
    int statusCode = 0;

    //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0);
    String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);

    String reqUrl = "";
    if (path.contains("http://") || path.contains("https://")) {
        reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query);
    } else {
        reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query);
    }
    Log.i(TAG, "submit url=" + reqUrl);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);

    try {
        HttpGet get = new HttpGet(reqUrl);
        if (token != null) {
            get.setHeader("Authorization", "Token " + token);
        }

        HttpResponse response;
        response = client.execute(get);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        statusCode = response.getStatusLine().getStatusCode();
        Log.v(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
            InputStream in = entity.getContent();
            rawData = FileUtil.convertInputStreamToString(in);

            entity.consumeContent();
        }

    } catch (ClientProtocolException e) {
        Log.e(TAG, "error post data", e);
    } catch (IOException e) {
        Log.e(TAG, "Can't connect server", e);
    } finally {
        client.getConnectionManager().shutdown();
    }

    ResponseObject respObj = new ResponseObject(statusCode, jsonObj);
    respObj.setRawData(rawData);
    return respObj;
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Gets the.//from   w  ww  . j a  v a  2 s.co  m
 * 
 * @param url
 *            the url
 * @param cap
 *            the cap
 * @param downloadDir
 *            the download dir
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void get(String url, String cap, String downloadDir) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "download/" + cap;
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpGet get = new HttpGet(url);

    HttpResponse response = client.execute(get);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        final double filesize = ht.getContentLength();

        FileOutputStream out = new FileOutputStream(FileUtils.JoinPath(downloadDir, cap));
        OutputStreamProgress cout = new OutputStreamProgress(out, new ProgressListener() {

            @Override
            public void transfered(long bytes, float rate) {
                int percent = (int) ((bytes / filesize) * 100);
                String bar = ProgressUtils.progressBar("Download Progress: ", percent, rate);
                System.out.print("\r" + bar);
            }
        });

        ht.writeTo(cout);
        out.close();
        System.out.println();
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:com.vmware.vchs.publicapi.samples.HttpUtils.java

/**
 * This method returns an HttpClient instance wrapped to trust all HTTPS certificates.
 * /*  w ww .ja  v a 2 s  .c o m*/
 * @return HttpClient a new instance of HttpClient
 */
static HttpClient createHttpClient() {
    HttpClient base = new DefaultHttpClient();

    try {
        SSLContext ctx = SSLContext.getInstance("TLS");

        // WARNING: This creates a TrustManager that trusts all certificates and should not be used in production code.
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        ctx.init(null, trustAllCerts, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));

        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.dasein.cloud.google.HttpsConnection.java

public static String getJSON(String iss, String p12File) throws Exception {
    System.out.println("ISS : " + iss);
    System.out.println("P12File : " + p12File);

    HttpClient client = new DefaultHttpClient();
    List formparams = new ArrayList();
    formparams.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));
    formparams.add(new BasicNameValuePair("assertion", GenerateToken.getToken(iss, p12File)));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

    //      HttpClient client1 = new HttpClient();
    String url = "https://accounts.google.com/o/oauth2/token";
    //      System.out.println(url);
    //      PostMethod pm = new PostMethod(url); 
    //      pm.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //      pm.addRequestHeader("Host", "accounts.google.com");
    ////      pm.addRequestHeader("Host", "accounts.google.com");
    //      pm.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    //      pm.addParameter("assertion", GenerateToken.getData());
    ////      System.out.println(C.getData());
    ////from   w w  w .  ja  v a2  s  .c o m
    //      int statusCode = client1.executeMethod(pm);

    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httppost.setEntity(entity);
    HttpResponse httpResponse1 = client.execute(httppost);
    int s1 = httpResponse1.getStatusLine().getStatusCode();
    if (s1 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse1.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    }

    JSONObject obj1 = new JSONObject(printFile("D:\\google_out.txt"));
    String access_token = obj1.getString("access_token");
    String token_type = obj1.getString("token_type");
    String expires_in = obj1.getString("expires_in");
    String resource = "instances";
    url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/"
            + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
    String str = "{"
            + "\"image\": \"https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104\","
            + "\"machineType\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1\","
            + "\"name\": \"trial\","
            + "\"zone\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/\","
            + "\"networkInterfaces\": [ {  \"network\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/networks/default\" } ],"
            + "\"disks\": [ { \"type\": \"EPHEMERAL\",  \"deleteOnTerminate\": true  } ], \"metadata\": { \"items\": [ ],  \"kind\": \"compute#metadata\" }}";
    System.out.println(str);
    JSONObject json = new JSONObject(str);
    System.out.println("POST Methods : " + url);
    StringEntity se = new StringEntity(str);
    JSONObject json1 = new JSONObject();
    json1.put("image",
            "https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104");
    json1.put("machineType",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1");
    json1.put("name", "trial");
    json1.put("zone",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/");
    //json1.put("image", "https://www.googleapis.com/compute/v1beta13/projects/google/images/ubuntu-10-04-v20120621");
    System.out.println(" JSON 1 : " + json.toString() + " \n JSON 2 : " + json1.toString());
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("json", str));

    //              
    //               JSONObject jsonPayload = null;
    //               JSONObject obj = new JSONObject();
    //               
    //               try {
    //               obj.put("name", "vinotrial");
    //               obj.put("IPv4Range", "192.0.0.0/16");
    //               obj.put("description", "wrwer");
    //
    //               } catch (Exception e) {
    //                  
    //               }

    /*
    JSONObject jsonPayload = null;
    JSONObject obj = new JSONObject();
            
    try {
    obj.put("name", "testCreateStandardFirewall1734".toLowerCase());
    obj.put("description", "SSH allowed from anywhere");
    obj.put("network", "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev/networks/default");
    JSONArray sranges = new JSONArray();
    JSONArray allowed = new JSONArray();
    JSONObject allowedtemp = new JSONObject();
    JSONArray ports = new JSONArray();
    allowedtemp.put("IPProtocol", "tcp");
    ports.put("22");
    allowedtemp.put("ports", ports);
    allowed.put(allowedtemp);
    //               
    //               JSONObject allowedtemp1 = new JSONObject();
    //               JSONArray ports1 = new JSONArray();
    //               allowedtemp1.put("IPProtocol", "udp");
    //               ports1.put("1-65535");
    //               allowedtemp1.put("ports", ports1);
    //               allowed.put(allowedtemp1);
    //               
    //               
    //               
    //               JSONObject allowedtemp2 = new JSONObject();
    //               
    //               allowedtemp2.put("IPProtocol", "icmp");
    //               
    //               allowed.put(allowedtemp2);
            
            
    sranges.put("0.0.0.0/0");
    obj.put("sourceRanges", sranges);
    obj.put("allowed", allowed);
    } catch (Exception e) {
             
    }
            
            
    */

    //UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams1, "UTF-8");
    System.out.println("Creating an instance");
    HttpPost httppost1 = new HttpPost(url);
    httppost1.setHeader("Content-type", "application/json");
    //httppost1.addHeader("X-JavaScript-User-Agent", "trov");
    //httppost1.setEntity(se);
    //   httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    System.out.println("payload:" + json1.toString());
    System.out.println("url:" + url);
    StringEntity se1 = new StringEntity(json1.toString());
    se1.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost1.setEntity(se1);
    //

    HttpClient base = new DefaultHttpClient();
    SSLContext ctx = SSLContext.getInstance("TLS");
    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;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    HttpClient client1 = new DefaultHttpClient(ccm);

    //HttpClient client1 = new DefaultHttpClient();
    HttpResponse httpResponse2 = client1.execute(httppost1);
    int s2 = httpResponse2.getStatusLine().getStatusCode();
    if (s2 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse2.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    } else {
        System.out.println("Instance creation failed with error status " + s2);
        InputStream in = httpResponse2.getEntity().getContent();
        writeToFile(in, "D:\\google_out.txt");
        System.out.println(printFile("D:\\google_out.txt"));
    }

    String[] Zone = { "europe-west1-a", "europe-west1-b", "us-central1-a", "us-central1-b", "us-central2-a",
            "us-east1-a" };
    for (String zone : Zone) {
        //             {
        HttpClient client3 = new DefaultHttpClient();
        resource = "instances";
        System.out.println("listing the instances !");
        //      url= "https://www.googleapis.com/compute/v1beta13/projects/google/kernels?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
        //   url = "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        //         url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/instances?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        System.out.println("url : -----------" + url);

        JSONArray items = new JSONArray();

        HttpGet method = new HttpGet(url);

        HttpResponse httpResponse = client3.execute(method);
        int s = httpResponse.getStatusLine().getStatusCode();

        if (s == HttpStatus.SC_OK) {

            try {
                System.out.println("\nResponse from Server : ");
                //InputStream in = getResponseBody(gm);
                InputStream in = httpResponse.getEntity().getContent();
                writeToFile(in, "D:\\calendar_out.txt");
                String str1 = printFile("D:\\calendar_out.txt");
                System.out.println(str1);
                JSONObject jsonO = new JSONObject(str1);
                items = (JSONArray) jsonO.get("items");

                //   return printFile("D:\\calendar_out.txt");
            } catch (Exception e) {
                System.out.println("No response body !" + e.getLocalizedMessage());
            }

        } else
            System.out.println(httpResponse);

        for (int i = 0; i < items.length(); i++) {

            JSONObject item = (JSONObject) items.get(i);
            String name = null;
            if (item.has("name"))
                name = (String) item.get("name");
            //System.out.println("instance : " + name);

            if (!name.contains("default")) {
                System.out.println("Deleting the instance " + name);
                url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                        + resource + "/" + name + "?access_token=" + access_token
                        + "&token_type=Bearer&expires_in=3600";
                System.out.println("url : " + url);

                HttpDelete delMethod = new HttpDelete(url);
                HttpResponse httpResponse3 = client.execute(delMethod);
                int s3 = httpResponse3.getStatusLine().getStatusCode();
                if (s3 == HttpStatus.SC_OK) {

                    try {
                        System.out.println("\nResponse from Server : ");
                        //InputStream in = getResponseBody(gm);
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                        //   return printFile("D:\\calendar_out.txt");
                    } catch (Exception e) {
                        System.out.println("No response body !");

                    }

                } else {
                    System.out.println("Deleting failed with status : " + s3);
                    try {
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                    } catch (Exception e) {

                    }
                }
            }
        }

        //      https://www.googleapis.com/compute/v1beta13/projects/enstratus.com%3Aenstratus-dev/instances/trial
        //      GetMethod gm      = new GetMethod(url); 
        //      HttpMethodParams params = new HttpMethodParams();
        ////      params.setParameter("calendarId", "vidhyanallasamy%40gmail.com");
        //      gm.setParams(params);
        //
        //      statusCode = client1.executeMethod(gm);
        //      System.out.println("\nStatus Code : " + statusCode);
        //
        //      try {
        //         System.out.println("\nResponse from Server : ");
        //         InputStream in = getResponseBody(gm);
        //         writeToFile(in, "D:\\calendar_out.txt");
        //         System.out.println(printFile("D:\\calendar_out.txt"));
        //      } catch (Exception e) {
        //         System.out.println("No response body !");
        //      }\
    }
    return null;
}

From source file:org.trpr.platform.batch.impl.job.ha.service.FileUpload.java

/**
 * A generic method to execute any type of Http Request and constructs a response object
 * @param requestBase the request that needs to be exeuted
 * @return server response as <code>String</code>
 *///from   w w  w.j  a va 2  s.co m
public static String executeRequest(HttpRequestBase requestBase) {
    //The string holding the server response
    String responseString = "";
    InputStream responseStream = null;
    HttpClient client = new DefaultHttpClient();
    try {
        HttpResponse response = client.execute(requestBase);
        if (response != null) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                responseStream = responseEntity.getContent();
                if (responseStream != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                    String responseLine = br.readLine();
                    String tempResponseString = "";
                    while (responseLine != null) {
                        tempResponseString = tempResponseString + responseLine
                                + System.getProperty("line.separator");
                        responseLine = br.readLine();
                    }
                    br.close();
                    if (tempResponseString.length() > 0) {
                        responseString = tempResponseString;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while uploading file to server", e);
    }
    client.getConnectionManager().shutdown();
    return responseString;
}