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:net.zypr.api.Protocol.java

public JSONObject doStreamPost(APIVerbs apiVerb, Hashtable<String, String> urlParameters,
        Hashtable<String, String> postParameters, InputStream inputStream)
        throws APICommunicationException, APIProtocolException {
    if (!_apiEntity.equalsIgnoreCase("voice"))
        Session.getInstance().addActiveRequestCount();
    long t1 = System.currentTimeMillis();
    JSONObject jsonObject = null;//from ww w. j  a  va  2s .co m
    JSONParser jsonParser = new JSONParser();
    try {
        DefaultHttpClient httpclient = getHTTPClient();
        HttpPost httpPost = new HttpPost(buildURL(apiVerb, urlParameters));
        HttpProtocolParams.setUseExpectContinue(httpPost.getParams(), false);
        MultipartEntity multipartEntity = new MultipartEntity();
        if (postParameters != null)
            for (Enumeration enumeration = postParameters.keys(); enumeration.hasMoreElements();) {
                String key = enumeration.nextElement().toString();
                String value = postParameters.get(key);
                multipartEntity.addPart(key, new StringBody(value));
                Debug.print("HTTP POST : " + key + "=" + value);
            }
        if (inputStream != null) {
            InputStreamBody inputStreamBody = new InputStreamBody(inputStream, "binary/octet-stream");
            multipartEntity.addPart("audio", inputStreamBody);
        }
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() != 200)
            throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode()
                    + " - " + httpResponse.getStatusLine().getReasonPhrase());
        HttpEntity httpEntity = httpResponse.getEntity();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
        jsonObject = (JSONObject) jsonParser.parse(bufferedReader);
        bufferedReader.close();
        httpclient.getConnectionManager().shutdown();
    } catch (ParseException parseException) {
        throw new APIProtocolException(parseException);
    } catch (IOException ioException) {
        throw new APICommunicationException(ioException);
    } catch (ClassCastException classCastException) {
        throw new APIProtocolException(classCastException);
    } finally {
        if (!_apiEntity.equalsIgnoreCase("voice"))
            Session.getInstance().removeActiveRequestCount();
        long t2 = System.currentTimeMillis();
        Debug.print(buildURL(apiVerb, urlParameters) + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : "
                + jsonObject);
    }
    return (jsonObject);
}

From source file:com.serena.rlc.provider.tfs.client.TFSClient.java

/**
 * Execute a get request to TFS.//from ww w . ja  va  2s .  co  m
 *
 * @param whichApi  the API to use
 * @param path  the path for the specific request
 * @param parameters  parameters to send with the query
 * @return String containing the response body
 * @throws TFSClientException
 */
protected String processGet(VisualStudioApi whichApi, String path, String parameters)
        throws TFSClientException {
    String uri = createUrl(whichApi, path, parameters);

    logger.debug("Start executing TFS GET request to url=\"{}\"", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getTFSUsername(), getTFSPassword());
    getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    getRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    getRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);
    String result = "";

    try {
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        result = sb.toString();
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
        throw new TFSClientException("Server not available", ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    logger.debug("End executing TFS GET request to url=\"{}\" and receive this result={}", uri, result);

    return result;
}

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Programmatic invocation.//from w w w  . ja  va 2  s . c o m
 * @param configServer   the configuration server for creating the REST server
 * @param restServer   the specification of the REST server
 */
public void makeServer(ConfigServer configServer, RESTServer restServer)
        throws ClientProtocolException, IOException, FactoryConfigurationError {

    DefaultHttpClient client = new DefaultHttpClient();

    String host = configServer.getHost();
    int configPort = configServer.getPort();

    // TODO: SSL
    Authentication authType = configServer.getAuthType();
    if (authType != null) {
        List<String> prefList = new ArrayList<String>();
        if (authType == Authentication.BASIC)
            prefList.add(AuthPolicy.BASIC);
        else if (authType == Authentication.DIGEST)
            prefList.add(AuthPolicy.DIGEST);
        else
            throw new IllegalArgumentException("Unknown authentication type: " + authType.name());
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList);

        String configUser = configServer.getUser();
        String configPassword = configServer.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(host, configPort),
                new UsernamePasswordCredentials(configUser, configPassword));
    }

    BasicHttpContext context = new BasicHttpContext();

    StringEntity content;
    try {
        content = new StringEntity(restServer.toXMLString());
    } catch (XMLStreamException e) {
        throw new IOException("Could not create payload to bootstrap server.");
    }
    content.setContentType("application/xml");

    HttpPost poster = new HttpPost("http://" + host + ":" + configPort + "/v1/rest-apis");
    poster.setEntity(content);

    HttpResponse response = client.execute(poster, context);
    //poster.releaseConnection();

    StatusLine status = response.getStatusLine();

    int statusCode = status.getStatusCode();
    String statusPhrase = status.getReasonPhrase();

    client.getConnectionManager().shutdown();

    if (statusCode >= 300) {
        throw new RuntimeException("Failed to create REST server: " + statusCode + " " + statusPhrase + "\n"
                + "Please check the server log for detail");
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.ClusteredWebSimpleTestCase.java

@Test
@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 IOException {
    DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + "simple";
    String url2 = baseURL2.toString() + "simple";

    try {//from  w w  w  . ja  v  a  2s  .  com
        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:org.jboss.as.test.clustering.cluster.web.ClusteredWebTestCase.java

@Test
@OperateOnDeployment("deployment-1") // For change, operate on the 2nd deployment first
public void testSessionReplication(@ArquillianResource(SimpleServlet.class) URL baseURL)
        throws IllegalStateException, IOException, InterruptedException {
    DefaultHttpClient client = new DefaultHttpClient();

    // ARQ-674 Ouch, hardcoded URL will need fixing. ARQ doesnt support @OperateOnDeployment on 2.
    String url1 = baseURL.toString() + "simple";
    String url2 = "http://127.0.0.1:8080/distributable/simple";

    try {/*from ww  w  .  j  a  v  a2 s. c om*/
        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
        Thread.sleep(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:org.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testDigestAuthenticatedPost() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Perform a HEAD, and extract the realm and nonce
    HttpHead head = new HttpHead(BASE_URL);
    head.addHeader("X-Requested-Auth", "Digest");
    HttpResponse headResponse = httpclient.execute(head);
    Header authHeader = headResponse.getHeaders("WWW-Authenticate")[0];
    String nonce = null;/*from w  ww  .j  av a 2  s  . c  o  m*/
    String realm = null;
    for (HeaderElement element : authHeader.getElements()) {
        if ("nonce".equals(element.getName())) {
            nonce = element.getValue();
        } else if ("Digest realm".equals(element.getName())) {
            realm = element.getValue();
        }
    }
    // Build the post
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account",
            "CHANGE_ME");
    HttpPost post = new HttpPost(BASE_URL + "/capture-admin/agents/testagent");
    post.addHeader("X-Requested-Auth", "Digest");
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("state", "idle"));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    // Add the previously obtained nonce
    HttpContext localContext = new BasicHttpContext();
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", realm);
    digestAuth.overrideParamter("nonce", nonce);
    localContext.setAttribute("preemptive-auth", digestAuth);

    // Send the POST
    try {
        HttpResponse response = httpclient.execute(post, localContext);
        String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals("testagent set to idle", content);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

/**
 * Internal sendRequest, performs the HTTP request and returns the result document.
 *///from w  w  w .  j a v a 2 s.  c om
private Document doSendRequest(final Document requestDocument, final SoapAction soapAction) {
    final DefaultHttpClient client = new DefaultHttpClient();
    try {
        configureHttpClient(client);
        final HttpContext context = new BasicHttpContext();
        final HttpPost request = new HttpPost(targetURL.toURI());

        if (soapAction != null) {
            request.setHeader("SOAPAction", soapAction.getValue());
        }

        final String requestBody = toString(requestDocument);
        logger.trace("Request:\nPOST {}\n{}", targetURL, requestBody);

        final HttpEntity entity = createEntity(requestBody);
        request.setEntity(entity);

        final HttpResponse response = client.execute(request, context);

        logResponseHeaders(response);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new WinRmRuntimeIOException(String.format("Unexpected HTTP response on %s:  %s (%s)",
                    targetURL, response.getStatusLine().getReasonPhrase(),
                    response.getStatusLine().getStatusCode()));
        }

        final String responseBody = handleResponse(response, context);
        Document responseDocument = DocumentHelper.parseText(responseBody);

        logDocument("Response body:", responseDocument);

        return responseDocument;
    } catch (WinRmRuntimeIOException exc) {
        throw exc;
    } catch (Exception exc) {
        throw new WinRmRuntimeIOException("Error when sending request to " + targetURL, requestDocument, null,
                exc);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.da.img.SoStroyAllList.java

protected void executeURL(String p_page, String p_author_id, String p_gnum)
        throws IOException, ClientProtocolException, URISyntaxException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*ww w .  j av  a2  s .c  o m*/
        List<AuthorVo> lstAuthor = executeAuthorList(p_page, p_author_id, p_gnum);
        HttpGet httpget = executeLogin(httpclient);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = "";
        // http://story.soraspace.info/honor/honor_list_02.php
        // http://story.soraspace.info/honor/honor_list_03.php
        // http://story.soraspace.info/honor/honor_list_04.php
        // http://story.soraspace.info/honor/honor_list_05.php
        List<ImageVo> lst = null;
        int max_page = 10000;
        int init_page = 1;
        if (!"".equals(StringUtils.stripToEmpty(p_page))) {
            init_page = Integer.parseInt(p_page);
        }
        // init_page = 17;
        for (AuthorVo vo : lstAuthor) {
            SAVE_DIR = STORY_DIR + "/story/" + vo.getAuthorAlias() + "(" + vo.getAuthorId() + ")";
            p_author_id = vo.getAuthorId();
            for (int i = init_page; i < max_page; i++) {
                lst = getBoardList(httpclient, httpget, responseHandler, p_gnum, String.valueOf(i),
                        p_author_id);
                System.out.println("Story Size: " + lst.size());
                if (lst.size() < 1) {
                    break;
                }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        System.out.println("ERROR: " + ex.getLocalizedMessage());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}