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:ch.entwine.weblounge.test.harness.content.PageContentTest.java

/**
 * Tests that the work version of a page is returned.
 * //from  w  w w .j  a v  a 2  s  .  c  o m
 * @param serverUrl
 *          the base server url
 * @throws Exception
 *           if the test fails
 */
private void testWorkPage(String serverUrl) throws Exception {
    logger.info("Preparing test of regular page content");

    // Prepare the request
    logger.info("Testing regular page output as an editor");

    String requestUrl = UrlUtils.concat(serverUrl, requestPath, "work.html");

    logger.info("Sending request to the work version of {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("Cookie", "weblounge.editor=true");

    // Send and the request and examine the response
    logger.debug("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Get the document contents
        Document xml = TestUtils.parseXMLResponse(response);

        // Look for included pagelet's properties
        String property = XPathHelper.valueOf(xml, "/html/body/div[@id='main']//span[@id='property']");
        assertNotNull("Content of pagelet property 'headline' not found", property);
        assertEquals("Element property does not match", "false", property);

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends a {@link MultipartEntity} post with text and image files.
 *
 * @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 Exception if something goes wrong.
 *//*from   w w  w  .ja v a  2  s .  co  m*/
public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap,
        HashMap<String, File> filesMap) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(url);

    if (user != null && pwd != null && user.trim().length() > 0 && pwd.trim().length() > 0) {
        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.bluexml.side.deployer.alfresco.directcopy.AlfrescoHotDeployerHelper.java

public static String executeRequest(HttpClient httpclient, HttpRequestBase post) throws Exception {
    String responseS = "";
    // Execute the request
    HttpResponse response;//from  w  w w.  ja  v  a2  s  .c  o m

    System.out.println("AlfrescoHotDeployerHelper.executeRequest() request:" + post);
    System.out.println("AlfrescoHotDeployerHelper.executeRequest() URI :" + post.getURI());

    response = httpclient.execute(post);

    // Examine the response status
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    System.out.println(response.getStatusLine());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response

            responseS = readBuffer(responseS, reader);

        } catch (IOException ex) {

            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;

        } catch (RuntimeException ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying 
            // connection and release it back to the connection manager.

            post.abort();
            throw ex;

        } finally {

            // Closing the input stream will trigger connection release
            instream.close();

        }

        // 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 != 200) {
        throw new Exception("Request Fail HTTP response :" + statusLine);
    }
    return responseS;
}

From source file:id.nci.stm_9.HkpKeyServer.java

@Override
public String get(long keyId) throws QueryException {
    HttpClient client = new DefaultHttpClient();
    try {/*w  w  w .j a  va  2  s  . co m*/
        HttpGet get = new HttpGet("http://" + mHost + ":" + mPort + "/pks/lookup?op=get&search=0x"
                + PgpKeyHelper.convertKeyToHex(keyId));

        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new QueryException("not found");
        }

        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        String data = readAll(is, EntityUtils.getContentCharSet(entity));
        Matcher matcher = PgpHelper.PGP_PUBLIC_KEY.matcher(data);
        if (matcher.find()) {
            return matcher.group(1);
        }
    } catch (IOException e) {
        // nothing to do, better luck on the next keyserver
    } finally {
        client.getConnectionManager().shutdown();
    }

    return null;
}

From source file:ch.entwine.weblounge.test.harness.content.HTMLActionTest.java

/**
 * Tests whether action output can be redirected to certain pages by providing
 * a target url./*  w  w w. j  a  v a2s .  c  o  m*/
 * 
 * @param serverUrl
 *          the server url
 */
private void testOverridenTargetPage(String serverUrl) {
    logger.info("Preparing test of greeter action");

    // Prepare the request
    logger.info("Testing action target page overriding");

    StringBuffer requestUrl = new StringBuffer(targetedActionPath);
    requestUrl.append("?").append(HTMLAction.TARGET_PAGE).append("=%2F");
    HttpGet request = new HttpGet(UrlUtils.concat(serverUrl, requestUrl.toString()));

    // Send the request and make sure it ends up on the expected page
    logger.info("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Get the document contents
        Document xml = TestUtils.parseXMLResponse(response);

        // Make sure it is rendered on the home page
        String testSuiteTitle = XPathHelper.valueOf(xml, "/html/body/h1");
        assertEquals("Action is not rendered on start page", "Welcome to the Weblounge 3.0 testpage!",
                testSuiteTitle);

    } catch (Throwable e) {
        fail("Request to " + request.getURI() + " failed" + e.getMessage());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:co.forsaken.api.json.JsonWebCall.java

public <T> T executeGet(Class<T> retType, boolean encapsulate) throws Exception {
    if (_log)/*from   ww  w. j av a 2s  .c  om*/
        System.out.println("Requested: [" + _url + "]");
    try {
        canConnect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    HttpClient httpClient = new DefaultHttpClient(_connectionManager);
    InputStream in = null;
    T returnData = null;
    String res = null;

    try {
        HttpGet request = new HttpGet(_url);
        request.setHeader("Content-Type", "application/json");
        HttpResponse response = httpClient.execute(request);
        if (response != null) {
            in = response.getEntity().getContent();
            res = convertStreamToString(in);
            if (encapsulate) {
                res = "{\"data\":" + res + "}";
            }
            returnData = new Gson().fromJson(res, retType);
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        httpClient.getConnectionManager().shutdown();
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    if (_log)
        System.out.println("Returned: [" + _url + "] [" + res + "]");
    return returnData;
}

From source file:edu.harvard.liblab.ecru.SolrClient.java

/**
 * Invokes the submitted URL with an application/xml accept header
 * and returns the response body as a string
 * @param url//from w ww.  j  ava  2  s  . co  m
 * @return
 * @throws SolrClientException
 */
public String callURLGet(String url) throws SolrClientException {
    int statusCode = -1;

    HttpClient client = createHttpClient();
    HttpGet request = new HttpGet(url);

    request.addHeader("user-agent", this.userAgent);
    request.addHeader("accept", "application/xml");

    try {
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();

        statusCode = status.getStatusCode();
        String responseString = EntityUtils.toString(response.getEntity());
        if (statusCode == HttpStatus.SC_OK) {
            return responseString;
        } else {
            throw new Exception(responseString);
        }
    } catch (Exception e) {
        String error = e.getMessage();
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            error = url + " could not be reached";
        }
        throw new SolrClientException("Error calling Solr service. " + error + "Status code=" + statusCode, e);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.caboclo.clients.ApiClient.java

protected void downloadURL(String url, ByteArrayOutputStream bos, Map<String, String> headers)
        throws IllegalStateException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    for (String key : headers.keySet()) {
        String value = headers.get(key);

        httpget.setHeader(key, value);//www.j ava  2 s .  c o  m
    }

    HttpResponse response = httpclient.execute(httpget);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            InputStream instream = entity.getContent();
            BufferedInputStream bis = new BufferedInputStream(instream);

            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            throw ex;
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
            httpget.abort();
            throw ex;
        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.sociotech.communitymashup.framework.java.apiwrapper.CommunityMashupApi.java

/**
 * Processes a post request against the given url.
 * /*  ww w . java2s. c  o  m*/
 * @param url
 *            Url for the get request.
 * @param parameterMap
 * @return The response as string
 * @throws MashupConnectionException
 *             If connection was not successful
 */
@SuppressWarnings("unused")
private String doPost(String url, Map<String, String> parameterMap) throws MashupConnectionException {
    String result = null;

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

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

    // add all post parameter
    for (String key : parameterMap.keySet()) {
        nameValuePairs.add(new BasicNameValuePair(key, parameterMap.get(key)));
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        result = httpClient.execute(post, responseHandler);
    } catch (Exception e) {
        throw new MashupConnectionException(e, url);
    } finally {
        // client is no longer needed
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:ua.kiev.doctorvera.utils.SMSGateway.java

@SuppressWarnings("deprecation")
public ArrayList<String> send(String phone, String sms) {
    ArrayList<String> result = new ArrayList<String>();
    final String MESSAGE = "<message><service id='single' source='" + FROM + "'/><to>" + phone
            + "</to><body content-type='text/plain'>" + sms + "</body></message>";

    @SuppressWarnings("resource")
    HttpClient httpclient = new DefaultHttpClient();
    String xml = null;//from w  w w. j  a v  a  2 s.  c  om
    try {
        HttpPost httpPost = new HttpPost(SMS_SEND_URL);

        StringEntity entity = new StringEntity(MESSAGE, "UTF-8");
        entity.setContentType("text/xml");
        entity.setChunked(true);
        httpPost.setEntity(entity);
        httpPost.addHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(LOGIN, PASS), "UTF-8", false));
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        LOG.info("Sending SMS: " + (response.getStatusLine().getStatusCode() == 200));
        xml = EntityUtils.toString(resEntity);
    } catch (Exception e) {
        LOG.severe("" + e.getStackTrace());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    //parsing xml result
    Document doc = loadXMLFromString(xml);
    NodeList nl = doc.getElementsByTagName("status");
    Element status = (Element) nl.item(0);

    result.add(0, status.getAttribute("id").toString()); //tracking id at position 0
    result.add(1, status.getAttribute("date").toString()); //date at position 1
    result.add(2, getElementValue(status.getFirstChild())); //state at position 2
    return result;
}