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:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public boolean testDHISServerDetails(String url, String user, String pass) {
    URL testURL;//from   w  w  w  .  j ava2 s . c o  m
    Boolean success = true;

    // Check if the URL makes sense
    try {
        testURL = new URL(url + "/api/resources"); // Add the root API
                                                   // endpoint to the URL
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    }

    HttpHost targetHost = new HttpHost(testURL.getHost(), testURL.getPort(), testURL.getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        HttpGet httpGet = new HttpGet(testURL.toURI());
        Credentials creds = new UsernamePasswordCredentials(user, pass);
        Header bs = new BasicScheme().authenticate(creds, httpGet, localcontext);
        httpGet.addHeader("Authorization", bs.getValue());
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Accept", "application/json");

        HttpResponse response = httpclient.execute(targetHost, httpGet, localcontext); // Execute
                                                                                       // the
                                                                                       // test
                                                                                       // query

        if (response.getStatusLine().getStatusCode() != 200) {
            success = false;

        }
    } catch (Exception ex) {
        ex.printStackTrace();
        success = false;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return success;
}

From source file:com.adam.aslfms.service.Scrobbler.java

/**
 * /*from  w w w  . jav a2 s. c om*/
 * @return a {@link ScrobbleResult} struct with some info
 * @throws BadSessionException
 * @throws TemporaryFailureException
 */
public void scrobbleCommit(HandshakeResult hInfo, Track[] tracks)
        throws BadSessionException, TemporaryFailureException {

    DefaultHttpClient http = new DefaultHttpClient();
    HttpPost request = new HttpPost(hInfo.scrobbleUri);

    List<BasicNameValuePair> data = new LinkedList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("s", hInfo.sessionId));

    for (int i = 0; i < tracks.length; i++) {
        Track track = tracks[i];
        String is = "[" + i + "]";
        data.add(new BasicNameValuePair("a" + is, track.getArtist()));
        data.add(new BasicNameValuePair("b" + is, track.getAlbum()));
        data.add(new BasicNameValuePair("t" + is, track.getTrack()));
        data.add(new BasicNameValuePair("i" + is, Long.toString(track.getWhen())));
        data.add(new BasicNameValuePair("o" + is, track.getSource()));
        data.add(new BasicNameValuePair("l" + is, Integer.toString(track.getDuration())));
        data.add(new BasicNameValuePair("n" + is, track.getTrackNr()));
        data.add(new BasicNameValuePair("m" + is, track.getMbid()));
        data.add(new BasicNameValuePair("r" + is, track.getRating()));
    }

    try {
        request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = http.execute(request, handler);
        String[] lines = response.split("\n");
        if (response.startsWith("OK")) {
            Log.i(TAG, "Scrobble success: " + getNetApp().getName());
        } else if (response.startsWith("BADSESSION")) {
            throw new BadSessionException("Scrobble failed because of badsession");
        } else if (response.startsWith("FAILED")) {
            String reason = lines[0].substring(7);
            throw new TemporaryFailureException("Scrobble failed: " + reason);
        } else {
            throw new TemporaryFailureException("Scrobble failed weirdly: " + response);
        }

    } catch (ClientProtocolException e) {
        throw new TemporaryFailureException(TAG + ": " + e.getMessage());
    } catch (IOException e) {
        throw new TemporaryFailureException(TAG + ": " + e.getMessage());
    } finally {
        http.getConnectionManager().shutdown();
    }
}

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

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

    // check Cache Response Headers (eTag and Last-Modified)
    if (isAtomPub || isBrowser) {
        RepositoryInfo ri = session.getRepositoryInfo();
        String uri = ri.getThinClientUri() + ri.getId() + "/";
        uri += isAtomPub ? "content?id=" : "root?objectId=";
        uri += file.getId();// ww  w. jav a2s.co m
        String eTag = file.getPropertyValue("nuxeo:contentStreamDigest");
        GregorianCalendar lastModifiedCalendar = file.getPropertyValue("dc:modified");
        String lastModified = DateUtil.formatDate(lastModifiedCalendar.getTime());
        String encoding = Base64.encodeBytes(new String(USERNAME + ":" + PASSWORD).getBytes());
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        HttpResponse response = null;
        request.setHeader("Authorization", "Basic " + encoding);
        try {
            request.setHeader("If-None-Match", eTag);
            response = client.execute(request);
            assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
            request.removeHeaders("If-None-Match");
            request.setHeader("If-Modified-Since", lastModified);
            response = client.execute(request);
            String debug = "lastModified=" + lastModifiedCalendar.getTimeInMillis() + " If-Modified-Since="
                    + lastModified + " NuxeoContentStream last=" + NuxeoContentStream.LAST_MODIFIED;
            // TODO NXP-16198 there are still timezone issues here
            // @Ignore
            // assertEquals(debug, 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:org.dasein.cloud.vcloud.vCloudMethod.java

protected @Nonnull HttpClient getClient(boolean forAuthentication) throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }//from  ww  w  .j a  v  a  2s.  co m
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    if (forAuthentication) {
        String accessPublic = null;
        String accessPrivate = null;
        try {
            List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                    accessPublic = new String(keyPair[0], "utf-8");
                    accessPrivate = new String(keyPair[1], "utf-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        String password = accessPrivate;
        String userName;

        if (matches(getAPIVersion(), "0.8", "0.8")) {
            userName = accessPublic;
        } else {
            userName = accessPublic + "@" + ctx.getAccountNumber();
        }

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    }
    return client;
}

From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java

public void go() {
    DefaultHttpClient client = null;
    try {/*from w ww. j a va2 s.c o  m*/
        prepareForResponse();

        if (altInput == null) {
            client = new DefaultHttpClient();

            // Set up preemptive Basic Authentication
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
            client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

            BasicHttpContext localcontext = new BasicHttpContext();
            BasicScheme basicAuth = new BasicScheme();
            localcontext.setAttribute("preemptive-auth", basicAuth);
            client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0);

            if (zip) {
                client.addRequestInterceptor(new GZipRequestInterceptor());
                client.addResponseInterceptor(new GZipResponseInterceptor());
            }

            HttpPost post = new HttpPost(url);

            try {
                setPostData(post);
                HttpResponse response = client.execute(post, localcontext);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    System.err.println(
                            "Error: Web Service response code of: " + response.getStatusLine().getStatusCode());
                    return;
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    parser.parseResponse(ids.size(), entity.getContent());
                }

            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        } else { // Alternate input (typically from a file) for testing
            try {
                parser.parseResponse(ids.size(), altInput);
            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        }
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
    /*
    try {
    parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump")));
    } catch (IOException e) {
    e.printStackTrace(); 
    }
    */

}

From source file:com.tmount.business.cloopen.util.CcopHttpClient.java

/**
 * SSL//from www. jav  a  2s . c  o m
 * @param hostname ??IP??
 * @param protocol ????TLS-??
 * @param port ??
 * @param scheme ????
 * @return HttpClient
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public DefaultHttpClient registerSSL(String hostname, String protocol, int port, String scheme)
        throws NoSuchAlgorithmException, KeyManagementException {

    //HttpClient
    DefaultHttpClient httpclient = new DefaultHttpClient();
    //SSL
    SSLContext ctx = SSLContext.getInstance(protocol);
    //???
    X509TrustManager tm = new X509TrustManager() {

        /**
         * ??
         */
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            //?   ?   
        }

        /**
         * ???
         * @param chain ?
         * @param authType ???authTypeRSA
         */
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            if (chain == null || chain.length == 0)
                throw new IllegalArgumentException("null or zero-length certificate chain");
            if (authType == null || authType.length() == 0)
                throw new IllegalArgumentException("null or zero-length authentication type");

            boolean br = false;
            Principal principal = null;
            for (X509Certificate x509Certificate : chain) {
                principal = x509Certificate.getSubjectX500Principal();
                if (principal != null) {
                    br = true;
                    return;
                }
            }
            if (!br) {
                throw new CertificateException("????");
            }
        }

        /**
         * CA??
         */
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };

    //?SSL
    ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
    //SSL
    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme(scheme, port, socketFactory);
    //SSL
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    return httpclient;
}

From source file:org.ryancutter.barcajolt.BarcaJolt.java

/**
 * Execute GET and collect response//from www . jav  a2 s  .c  om
 * 
 * @param getURL Requested GET operation. Will be appended to HOST.
 * 
 * @return JSONObject Results of GET operation. Will return null for HTTP status codes other
 * than 200.
 */
private JSONObject get(String getURL, boolean arrayResult) {
    // set up DefaultHttpClient and other objects
    StringBuilder builder = new StringBuilder();
    DefaultHttpClient client = new DefaultHttpClient();

    HttpHost host = new HttpHost(mHost, mPort, mProtocol);
    HttpGet get = new HttpGet(getURL);

    client.getCredentialsProvider().setCredentials(new AuthScope(host.getHostName(), host.getPort()),
            new UsernamePasswordCredentials(mUsername, mPassword));

    JSONObject jObject = null;
    try {
        // execute GET and collect results if valid response
        HttpResponse response = client.execute(host, get);

        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();
        if (statusCode == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line);
            }

            try {
                // check if this is the result of BarcaJolt.getDBs(). since Cloudant returns a JSONArray 
                // rather than JSONObject for /_all_dbs requests, this class temporarily wraps the array
                // like {"dbs":["database1", "database2"]}. unwrapped in BarcaJolt.getDBs()
                if (arrayResult) {
                    builder.insert(0, "{'dbs' : ");
                    builder.append("}");
                }

                jObject = new JSONObject(builder.toString());
            } catch (JSONException e) {
                Log.e(TAG, "JSONException converting StringBuilder to JSONObject", e);
            }
        } else {
            // we only want to process 200's
            // TODO process non-200's in a more clever way
            Log.e(TAG, "Bad HttoResponse status: " + new Integer(statusCode).toString());
            return null;
        }
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException", e);
    } catch (IOException e) {
        Log.e(TAG, "DefaultHttpClient IOException", e);
    }

    // let go of resources
    client.getConnectionManager().shutdown();

    return jObject;
}

From source file:org.jboss.as.test.clustering.xsite.XSiteBackupForTestCase.java

@Test
public void testPutRelayedToBackups(
        @ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2,
        @ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_3) URL baseURL3,
        @ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_4) URL baseURL4)

        throws IllegalStateException, IOException, InterruptedException {

    DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + "cache?operation=put&key=a&value=100";
    String url2 = baseURL2.toString() + "cache?operation=get&key=a";
    String url3 = baseURL3.toString() + "cache?operation=get&key=a";
    String url4 = baseURL4.toString() + "cache?operation=get&key=a";

    try {/* w w  w  . ja v a 2 s  .  c  om*/
        // put a value to LON-0
        System.out.println("Executing HTTP request: " + url1);
        HttpResponse response = client.execute(new HttpGet(url1));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        response.getEntity().getContent().close();
        System.out.println("Executed HTTP request");

        // Lets wait for the session to replicate
        waitForReplication(GRACE_TIME_TO_REPLICATE);

        // do a get on LON-1
        System.out.println("Executing HTTP request: " + url2);
        response = client.execute(new HttpGet(url2));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(100, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();
        System.out.println("Executed HTTP request");

        // do a get on NYC-0
        System.out.println("Executing HTTP request: " + url3);
        response = client.execute(new HttpGet(url3));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(100, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();
        System.out.println("Executed HTTP request");

        // do a get on SFO-0
        System.out.println("Executing HTTP request: " + url4);
        response = client.execute(new HttpGet(url4));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(100, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();
        System.out.println("Executed HTTP request");
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:cn.geowind.takeout.verify.JsonRestApi.java

public String sendCall(String accountSid, String authToken, String appId, String to, String verifyCode)
        throws KeyManagementException, NoSuchAlgorithmException {
    String result = "";
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("sandboxapp.cloopen.com", "TLS", 8883, "https");
    try {//  w w w.j  a  va  2  s.  co  m
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);
        // md5(Id + ? + )
        String sig = accountSid + authToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);

        StringBuffer sb = new StringBuffer();
        String url = sb.append(TEST_SMS_BASE_URL).append(SMS_VERSION).append("/Accounts/").append(accountSid)
                .append("/Calls").append("/VoiceVerify").append("?sig=").append(signature).toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);// base64(Id + ? +
        // )
        JSONObject obj = new JSONObject();
        obj.put("to", to);
        obj.put("appId", appId);
        obj.put("verifyCode", verifyCode);
        obj.put("playTimes", "3");
        String data = obj.toString();

        System.out.println("---------------------------- SendSMS for JSON begin----------------------------");
        System.out.println("data: " + data);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
        requestBody.setContentLength(data.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        // 
        HttpResponse response = httpclient.execute(httppost);

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    // ???
    return result;
}

From source file:org.jssec.android.https.imagesearch.HttpsImageSearch.java

@Override
protected Object doInBackground(String... params) {

    // HttpClient2?GET????????finally?shutdown?
    DefaultHttpClient client = new DefaultHttpClient();

    try {//w w  w . ja va 2 s .  c om
        // --------------------------------------------------------
        // 1??
        // --------------------------------------------------------

        // ?1 URI?https://??
        // ?2 ???????
        String search_url = Uri.parse("https://ajax.googleapis.com/ajax/services/search/images?v=1.0")
                .buildUpon().appendQueryParameter("q", params[0]).build().toString();
        HttpGet request = new HttpGet(search_url);
        HttpResponse response = client.execute(request);
        checkResponse(response);

        // ?3 HTTPS??????????????
        // ????3.2 ?????
        String result_json = EntityUtils.toString(response.getEntity(), "UTF-8");
        String image_url = new JSONObject(result_json).getJSONObject("responseData").getJSONArray("results")
                .getJSONObject(0).getString("url");

        // --------------------------------------------------------
        // 2???
        // --------------------------------------------------------

        // ?1 URI?https://??
        // ?2 ???????
        request = new HttpGet(image_url);
        response = client.execute(request);
        checkResponse(response);

        // ?3 HTTPS??????????????
        // ????3.2 ?????
        return EntityUtils.toByteArray(response.getEntity());
    } catch (SSLException e) {
        // ?4 SSLException?????????
        // ??????
        return e;
    } catch (Exception e) {
        return e;
    } finally {
        // ?HttpClientshutdown?
        client.getConnectionManager().shutdown();
    }
}