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.lastorder.pushnotifications.data.ImageDownloader.java

Bitmap downloadBitmap(String url, boolean isCanceled) throws IllegalArgumentException {
    final int IO_BUFFER_SIZE = 4 * 1024;

    // AndroidHttpClient is not allowed to be used from the main thread
    final DefaultHttpClient client = new DefaultHttpClient();
    //Si la url viene mal pincha

    // [IMG] [/] (creo)
    //Log.d("ImageDownloader", "URL: " + url.toString());
    final HttpGet getRequest = new HttpGet(url);

    try {/*from  w ww .  j  av a  2 s.co m*/
        HttpResponse response = client.execute(getRequest);

        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || isCanceled) {
            // Log.w("ImageDownloader", "Error " + statusCode +
            //       " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                // return BitmapFactory.decodeStream(inputStream);
                // Bug on slow connections, fixed in future release.
                return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    }
    client.getConnectionManager().shutdown();
    return null;
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public String getUrlData(String url) {
    String websiteData = null;/*from w  ww.j  a va  2  s .c  om*/

    if (!this.logged_in) {
        System.out.println("--1--- LOGIN START -----");
        this.logged_in = login();
        System.out.println("--1--- LOGIN END   -----");
    }

    try {
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient client = new DefaultHttpClient(httpParameters);
        client.setCookieStore(cookie_jar);
        // Log.d("cookie_jar", "->" + String.valueOf(cookie_jar));

        URI uri = new URI(url);
        HttpGet method = new HttpGet(uri);

        method.addHeader("User-Agent",
                "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
        method.addHeader("Pragma", "no-cache");

        HttpResponse res = client.execute(method);
        InputStream data = res.getEntity().getContent();
        websiteData = generateString(data);
        client.getConnectionManager().shutdown();

    } catch (SocketTimeoutException e2) {
        Log.d("HTMLDownloader", "Connectiont timout: " + e2);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnknownHostException x) {
        Log.d("HTMLDownloader", ": " + x);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return websiteData;
}

From source file:org.jboss.as.test.integration.security.loginmodules.common.Utils.java

public static void makeCall(String URL, String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from   w  w w .  j  a  va 2  s  .  c o  m*/
        HttpGet httpget = new HttpGet(URL);

        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        // We should get the Login Page
        StatusLine statusLine = response.getStatusLine();
        System.out.println("Login form get: " + statusLine);
        assertEquals(200, statusLine.getStatusCode());

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // We should now login with the user name and password
        HttpPost httpost = new HttpPost(URL + "/j_security_check");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", user));
        nvps.add(new BasicNameValuePair("j_password", pass));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        statusLine = response.getStatusLine();

        // Post authentication - we have a 302
        assertEquals(302, statusLine.getStatusCode());
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();

        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);

        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // Either the authentication passed or failed based on the expected status code
        statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } 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:IoTatWork.NotifyResolutionManager.java

/**
 * /*from  w w  w  . jav a2 s . c  om*/
 * @param notification
 * @return
 */
private boolean sendNotification(PendingResolutionNotification notification) {
    String xmlString = notification.toXML();

    String revocationPut = notification.getNotificationUrl() + notification.getRevocationHash();
    System.out.println("\nProcessing notification: " + revocationPut + "\n" + notification.toXML());
    // TODO logEvent
    //IoTatWorkApplication.logger.info("Sending pending resolution notification: "+revocationPut);
    IoTatWorkApplication.logger.info(LogMessage.SEND_RESOLUTION_NOTIFICATION + revocationPut);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut putRequest = new HttpPut(revocationPut);

    try {
        StringEntity input = new StringEntity(xmlString);

        input.setContentType("application/xml");
        putRequest.setEntity(input);

        HttpResponse response = httpClient.execute(putRequest);

        int statusCode = response.getStatusLine().getStatusCode();

        switch (statusCode) {
        case 200:
            IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_200);
            break;
        case 400:
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            String output = br.toString();
            /*
            while ((output = br.readLine()) != null) {
               System.out.println(output);
            }
            */
            JsonParser parser = new JsonParser();
            JsonObject jsonObj = (JsonObject) parser.parse(output);
            String code = jsonObj.get(JSON_PROCESSING_STATUS_CODE).getAsString();

            if (code.equals("NPR400")) {
                IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_400);
            } else if (code.equals("NPR450")) {
                IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_450);
            } else if (code.equals("NPR451")) {
                IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_451);
            }

            break;
        case 404:
            IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_404);
            break;
        case 500:
            IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_500);
            break;
        default:
            break;
        }

        httpClient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return true;

}

From source file:sand.actionhandler.weibo.UdaClient.java

public static String syn(String method, String machineno, String params) {
    String content = "";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/* w  ww  . j a v  a 2  s  . c o  m*/
        httpclient = createHttpClient();
        //      HttpGet httpget = new HttpGet("http://www.broken-server.com/");
        // 

        HttpGet httpget = new HttpGet(SERVER + method + "?no=" + machineno + "&" + params);

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        //           httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        // Execute HTTP request
        //System.out.println("executing request " + httpget.getURI());

        // DefaultHttpClient httpclient = new DefaultHttpClient();
        // cookie store
        CookieStore cookieStore = new BasicCookieStore();

        addCookie(cookieStore);
        // 
        httpclient.setCookieStore(cookieStore);

        logger.info("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

        //            System.out.println("----------------------------------------");
        //            System.out.println(response.getStatusLine());
        //            System.out.println(response.getLastHeader("Content-Encoding"));
        //            System.out.println(response.getLastHeader("Content-Length"));
        //            System.out.println("----------------------------------------");

        HttpEntity entity = response.getEntity();
        //System.out.println(entity.getContentType());

        if (entity != null) {
            content = EntityUtils.toString(entity);
            //                System.out.println(content);
            //                System.out.println("----------------------------------------");
            //                System.out.println("Uncompressed size: "+content.length());
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return content;
}

From source file:com.tmount.business.cloopen.restAPI.RestAPI.java

/**
* @brief            ?//from   ww w  .j av a  2  s  .c o  m
* @param accountSid      ?
* @param authToken      ?
*/
public String QueryAccountInfo(String accountSid, String authToken)
        throws NoSuchAlgorithmException, KeyManagementException {
    // ?
    String result = "";
    // HttpClient
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("app.cloopen.com", "TLS", 8883, "https");
    try {
        // 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);

        String url = (new StringBuilder(hostname)).append(":").append(port).append("/").append(softVer)
                .append("/Accounts/").append(accountSid).append("/AccountInfo?sig=").append(signature)
                .toString();
        // HttpGet
        System.out.println(url);
        HttpGet httpget = new HttpGet(url);
        setHttpHeader(httpget);
        String src = accountSid + ":" + timestamp;
        // base64(Id + ? +)
        String auth = eu.base64Encoder(src);
        httpget.setHeader("Authorization", auth);

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

        // ???
        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.jboss.additional.testsuite.jdkall.past.eap_6_4_x.clustering.cluster.web.ClusteredWebSimpleTestCase.java

@Test
@InSequence(3)/*from   w  w w . ja  v  a  2 s .  c o  m*/
@OperateOnDeployment(DEPLOYMENT_2)
// For change, operate on the 2nd deployment first
public void testSessionReplication(
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IllegalStateException, IOException, InterruptedException {
    DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + SimpleServlet.URL;
    String url2 = baseURL2.toString() + SimpleServlet.URL;

    try {
        HttpResponse response = client.execute(new HttpGet(url1));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();

        // Lets do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();

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

        // Now check on the 2nd server

        // Note that this DOES rely on the fact that both servers are running on the "same" domain,
        // which is '127.0.0.0'. Otherwise you will have to spoof cookies. @Rado
        response = client.execute(new HttpGet(url2));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(3, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();

        // Lets do one more check.
        response = client.execute(new HttpGet(url2));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

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

/**
 * SSL//w  w w. j a  va2  s.com
 * 
 * @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() {
        /**
         * CA??
         */
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        /**
         * ???
         * 
         * @param chain
         *            ?
         * @param authType
         *            ???authTypeRSA
         */
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws 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("????");
            }
        }

        /**
         * ??
         */
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };

    // ?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.meerkat.services.WebApp.java

/**
 * checkWebAppStatus//from w w w . j  a va  2  s.  c  om
 * 
 * @return WebAppResponse
 */
public WebAppResponse checkWebAppStatus() {
    // Set the response at this point to empty in case of no response at all
    setCurrentResponse("");
    int statusCode = 0;

    // Create an instance of HttpClient.
    MeerkatHttpClient meerkatClient = new MeerkatHttpClient();
    DefaultHttpClient httpclient = meerkatClient.getHttpClient();

    WebAppResponse response = new WebAppResponse();
    response.setResponseAppType();

    // Create a method instance.
    HttpGet httpget = new HttpGet(url);

    // Measure the response time
    Counter c = new Counter();
    c.startCounter();

    // Execute the method.
    HttpResponse httpresponse = null;
    try {
        httpresponse = httpclient.execute(httpget);
        // Set the http status
        statusCode = httpresponse.getStatusLine().getStatusCode();

    } catch (ClientProtocolException e) {
        log.error("Client Protocol Exception", e);

        response.setHttpStatus(0);

        response.setHttpTextResponse(e.toString());
        setCurrentResponse(e.toString());

        response.setContainsWebAppExpectedString(false);

        c.stopCounter();
        response.setPageLoadTime(c.getDurationSeconds());

        httpclient.getConnectionManager().shutdown();

        return response;
    } catch (IOException e) {
        log.error("IOException - " + e.getMessage());

        response.setHttpStatus(0);
        response.setHttpTextResponse(e.toString());
        setCurrentResponse(e.toString());

        response.setContainsWebAppExpectedString(false);

        c.stopCounter();
        response.setPageLoadTime(c.getDurationSeconds());

        httpclient.getConnectionManager().shutdown();

        return response;
    }

    response.setHttpStatus(statusCode);

    // Consume the response body
    try {
        httpresponse.getEntity().getContent().toString();
    } catch (IllegalStateException e) {
        log.error("IllegalStateException", e);
    } catch (IOException e) {
        log.error("IOException", e);
    }

    // Get the response
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent()));
    } catch (IllegalStateException e1) {
        log.error("IllegalStateException in http buffer", e1);
    } catch (IOException e1) {
        log.error("IOException in http buffer", e1);
    }

    String readLine;
    String responseBody = "";
    try {
        while (((readLine = br.readLine()) != null)) {
            responseBody += "\n" + readLine;
        }
    } catch (IOException e) {
        log.error("IOException in http response", e);
    }

    try {
        br.close();
    } catch (IOException e) {
        log.error("Closing BufferedReader", e);
    }

    response.setHttpTextResponse(responseBody);
    setCurrentResponse(responseBody);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    if (statusCode != HttpStatus.SC_OK) {
        log.warn("Httpstatus code: " + statusCode + " | Method failed: " + httpresponse.getStatusLine());
    }

    // Check if the response contains the expectedString
    if (getCurrentResponse().contains(expectedString)) {
        response.setContainsWebAppExpectedString(true);
    }

    // Stop the counter
    c.stopCounter();
    response.setPageLoadTime(c.getDurationSeconds());

    return response;
}

From source file:cauchy.android.tracker.PicasaWSUtils.java

public PicasaWSUtils(String user, String passwd) {
    userID = user;//w  w w. j  a v  a 2 s  .  c o m
    String url = "https://www.google.com/accounts/ClientLogin";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    try {
        HttpPost httpost = new HttpPost(new URI(url));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accountType", "GOOGLE"));
        nvps.add(new BasicNameValuePair("Email", userID));
        nvps.add(new BasicNameValuePair("Passwd", passwd));
        nvps.add(new BasicNameValuePair("service", "lh2"));
        nvps.add(new BasicNameValuePair("source", "companyName-applicationName-1.0"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Post, check and show the result (not really spectacular, but
        // works):
        response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        Log.d(LOG_TAG, "Google Login auth result = " + response.getStatusLine());

        if (entity != null) {
            InputStream toto = entity.getContent();
            long content_length = entity.getContentLength();
            StringBuffer content_buf = new StringBuffer();
            for (long i = 0; i < content_length; i++) {
                content_buf.append(((char) toto.read()));
            }

            int index = content_buf.toString().indexOf("Auth=");
            if (index != -1) {
                authString = content_buf.toString().substring(index + "Auth=".length(),
                        content_buf.toString().length() - 1);
            }
            entity.consumeContent();
        } else {
            Log.d(LOG_TAG, "Entity is null!");
        }

    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().closeExpiredConnections();
    }
}