Example usage for org.apache.http.impl.client DefaultHttpClient close

List of usage examples for org.apache.http.impl.client DefaultHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient close.

Prototype

public void close() 

Source Link

Usage

From source file:com.sugarcrm.candybean.examples.mobile.AppiumIosTest.java

@Test
public void testSessions() throws Exception {
    HttpGet request = new HttpGet("http://localhost:4723/wd/hub/sessions");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject = (JSONObject) new JSONParser().parse(EntityUtils.toString(entity));
    String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
    assertEquals(sessionId, jsonObject.get("sessionId"));
    httpClient.close();
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java

public static boolean deleteOAuthApplication(String user, String appName, String clientid, String host)
        throws DynamicClientRegistrationException {
    if (log.isDebugEnabled()) {
        log.debug("Invoking DCR service to remove OAuth application created for web app : " + appName);
    }/*from w  w w  . ja v a  2  s. co m*/
    DefaultHttpClient httpClient = getHTTPSClient();
    try {
        URI uri = new URIBuilder().setScheme(
                DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host)
                .setPath(
                        DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT)
                .setParameter("applicationName", appName).setParameter("userId", user)
                .setParameter("consumerKey", clientid).build();
        HttpDelete httpDelete = new HttpDelete(uri);
        HttpResponse response = httpClient.execute(httpDelete);
        int status = response.getStatusLine().getStatusCode();
        if (status == 200) {
            return true;
        }
    } catch (IOException e) {
        throw new DynamicClientRegistrationException(
                "Connection error occurred while constructing the payload for "
                        + "invoking DCR endpoint for unregistering the web-app : " + appName,
                e);
    } catch (URISyntaxException e) {
        throw new DynamicClientRegistrationException(
                "Exception occurred while constructing the URI for invoking "
                        + "DCR endpoint for unregistering the web-app : " + appName,
                e);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
    return false;
}

From source file:com.sugarcrm.candybean.examples.mobile.AppiumAndroidTest.java

@Test
public void testSessions() throws Exception {
    HttpGet request = new HttpGet("http://localhost:4723/wd/hub/sessions");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject = (JSONObject) new JSONParser().parse(EntityUtils.toString(entity));

    String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
    assertEquals(sessionId, jsonObject.get("sessionId"));
    httpClient.close();
}

From source file:com.ge.research.semtk.services.client.RestClient.java

/**
 * Make the service call.  /*ww w.j a  v a  2 s.  c o  m*/
 * @return an Object that can be cast to a JSONObject.  Subclasses may override and return a more useful Object.   
 */
public Object execute() throws ConnectException, Exception {

    // TODO can we do this before calling execute()?
    buildParametersJSON(); // set all parameters available upon instantiation

    System.out.println("EXECUTE ON " + this.conf.getServiceURL());

    if (parametersJSON == null) {
        throw new Exception("Service parameters not set");
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // immediate line below removed to perform htmml encoding in stream
    // HttpEntity entity = new ByteArrayEntity(parametersJSON.toJSONString().getBytes("UTF-8"));

    // js version:  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/%/g, "&#37;")

    HttpEntity entity = new ByteArrayEntity(parametersJSON.toString().getBytes("UTF-8"));
    HttpPost httppost = new HttpPost(this.conf.getServiceURL());
    httppost.setEntity(entity);
    httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

    // execute
    HttpHost targetHost = new HttpHost(this.conf.getServiceServer(), this.conf.getServicePort(),
            this.conf.getServiceProtocol());
    HttpResponse httpresponse = httpclient.execute(targetHost, httppost);

    // handle the output         
    String responseTxt = EntityUtils.toString(httpresponse.getEntity(), "UTF-8");
    httpclient.close();
    if (responseTxt == null) {
        throw new Exception("Received null response text");
    }
    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    if (responseTxt.length() < 500) {
        System.err.println("RestClient received: " + responseTxt);
    } else {
        System.err.println("RestClient received: " + responseTxt.substring(0, 200) + "... ("
                + responseTxt.length() + " chars)");
    }

    JSONObject responseParsed = (JSONObject) JSONValue.parse(responseTxt);
    if (responseParsed == null) {
        System.err.println("The response could not be transformed into json");
        if (responseTxt.contains("Error")) {
            throw new Exception(responseTxt);
        }
    }
    return responseParsed;
}

From source file:org.wso2.carbon.dynamic.client.web.proxy.OAuthEndpointProxy.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response issueAccessToken(MultivaluedMap<String, String> paramMap) {
    DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient();
    String host = DCRProxyUtils.getKeyManagerHost();
    Response response;//  w w  w  .  j  av  a 2  s  .  c om
    try {
        URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host).setPath(Constants.RemoteServiceProperties.OAUTH2_TOKEN_ENDPOINT).build();
        HttpHost httpHost = new HttpHost(uri.toString());
        CloseableHttpResponse serverResponse = httpClient.execute(httpHost, null);
        HttpEntity responseData = serverResponse.getEntity();
        int status = serverResponse.getStatusLine().getStatusCode();
        String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8);
        response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build();
    } catch (URISyntaxException | IOException e) {
        String msg = "Service invoke error occurred while registering client";
        log.error(msg, e);
        response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    } finally {
        httpClient.close();
    }
    return response;
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java

@Test
public void testSetParams() {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);
    params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, "pass");
    params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, "user");
    params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345);
    params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345);
    params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345);
    params.set(HttpClientUtil.PROP_USE_RETRY, false);
    DefaultHttpClient client = (DefaultHttpClient) HttpClientUtil.createClient(params);
    try {/*from ww  w  .  j  a v  a  2s  . co m*/
        assertEquals(12345, HttpConnectionParams.getConnectionTimeout(client.getParams()));
        assertEquals(PoolingClientConnectionManager.class, client.getConnectionManager().getClass());
        assertEquals(22345, ((PoolingClientConnectionManager) client.getConnectionManager()).getMaxTotal());
        assertEquals(32345,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getDefaultMaxPerRoute());
        assertEquals(42345, HttpConnectionParams.getSoTimeout(client.getParams()));
        assertEquals(HttpClientUtil.NO_RETRY, client.getHttpRequestRetryHandler());
        assertEquals("pass",
                client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)).getPassword());
        assertEquals("user", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234))
                .getUserPrincipal().getName());
        assertEquals(true, client.getParams().getParameter(ClientPNames.HANDLE_REDIRECTS));
    } finally {
        client.close();
    }
}

From source file:com.dumiduh.das.AnalyticsAPIInvoker.java

private String invoke(String url, String username, String pwd, String type) {
    TrustStrategyExt strategy = new TrustStrategyExt();

    String jsonString = "";
    try {/*  w ww . j  a va 2s . c  o m*/
        SSLSocketFactory sf = new SSLSocketFactory(strategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", Integer.parseInt(port), sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        DefaultHttpClient client = new DefaultHttpClient(ccm);
        HttpGet get = new HttpGet(url);
        String header = "Basic " + getBase64EncodedToken(username, pwd);
        get.setHeader("Authorization", header);

        HttpResponse resp = client.execute(get);
        if (type.equals("body")) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonString = result.toString();
        } else if (type.equals("header")) {
            StringBuffer result = new StringBuffer();
            Header[] headers = resp.getAllHeaders();
            for (Header h : headers) {

                result.append(h.getName() + " : " + h.getValue());
            }
            result.append("status code : " + resp.getStatusLine().getStatusCode());
            jsonString = result.toString();
        }

        client.close();

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    }

    return jsonString;
}

From source file:com.dumiduh.das.AnalyticsAPIInvoker.java

private String invokePost(String url, String username, String pwd, String type, String payload) {
    TrustStrategyExt strategy = new TrustStrategyExt();

    String jsonString = "";
    try {/* w w  w.  j  a v a2 s. c  om*/
        SSLSocketFactory sf = new SSLSocketFactory(strategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", Integer.parseInt(port), sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        DefaultHttpClient client = new DefaultHttpClient(ccm);

        StringEntity stringEntity = new StringEntity(payload);
        HttpPost post = new HttpPost();
        post.setEntity(stringEntity);
        String header = "Basic " + getBase64EncodedToken(username, pwd);
        post.setHeader("Authorization", header);
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Type", "application/json");

        HttpResponse resp = client.execute(post);
        if (type.equals("body")) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonString = result.toString();
        } else if (type.equals("header")) {
            StringBuffer result = new StringBuffer();
            Header[] headers = resp.getAllHeaders();
            for (Header h : headers) {

                result.append(h.getName() + " : " + h.getValue());
            }
            result.append("status code : " + resp.getStatusLine().getStatusCode());
            jsonString = result.toString();
        }

        client.close();

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonString;
}

From source file:org.wso2.identity.sample.webapp.APIInvoker.java

private String callRESTep(String ep) throws Exception {

    PlatformUtils.setKeyStoreProperties();
    PlatformUtils.setKeyStoreParams();/*  w w  w .ja  v  a  2 s  . c om*/

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        SSLSocketFactory sf = null;
        SSLContext sslContext = null;
        StringWriter writer;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);
        } catch (NoSuchAlgorithmException e) {
            //<YourErrorHandling>
        } catch (KeyManagementException e) {
            //<YourErrorHandling>
        }

        try {
            sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            //<YourErrorHandling>
        }
        Scheme scheme = new Scheme("https", 8243, sf);
        httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
        HttpGet get = new HttpGet(ep);

        // add header
        get.setHeader("Content-Type", "text/xml;charset=UTF-8");
        get.setHeader("Authorization", "Bearer " + oauthToken);
        get.setHeader("x-saml-assertion", SamlConsumerManager.getEncodedAssertion());

        CloseableHttpResponse response = httpClient.execute(get);
        try {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("API RESULT" + result);
            return result;
        } finally {
            response.close();
        }

    } finally {
        httpClient.close();
    }
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java

public static OAuthApplicationInfo createOAuthApplication(RegistrationProfile registrationProfile, String host)
        throws DynamicClientRegistrationException {
    if (log.isDebugEnabled()) {
        log.debug("Invoking DCR service to create OAuth application for web app : "
                + registrationProfile.getClientName());
    }//from   www.  j  ava2  s.c  om
    DefaultHttpClient httpClient = getHTTPSClient();
    String clientName = registrationProfile.getClientName();
    try {
        URI uri = new URIBuilder().setScheme(
                DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host)
                .setPath(
                        DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT)
                .build();
        Gson gson = new Gson();
        StringEntity entity = new StringEntity(gson.toJson(registrationProfile),
                DynamicClientWebAppRegistrationConstants.ContentTypes.CONTENT_TYPE_APPLICATION_JSON,
                DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8);
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();
        HttpEntity responseData = response.getEntity();
        String responseString = EntityUtils.toString(responseData,
                DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8);
        if (status != 201) {
            String msg = "Backend server error occurred while invoking DCR endpoint for "
                    + "registering service-provider upon web-app : '" + clientName
                    + "'; Server returned response '" + responseString + "' with HTTP status code '" + status
                    + "'";
            throw new DynamicClientRegistrationException(msg);
        }
        return getOAuthApplicationInfo(gson.fromJson(responseString, JsonElement.class));
    } catch (URISyntaxException e) {
        throw new DynamicClientRegistrationException(
                "Exception occurred while constructing the URI for invoking "
                        + "DCR endpoint for registering service-provider for web-app : " + clientName,
                e);
    } catch (UnsupportedEncodingException e) {
        throw new DynamicClientRegistrationException(
                "Exception occurred while constructing the payload for invoking "
                        + "DCR endpoint for registering service-provider for web-app : " + clientName,
                e);
    } catch (IOException e) {
        throw new DynamicClientRegistrationException("Connection error occurred while invoking DCR endpoint for"
                + " registering service-provider for web-app : " + clientName, e);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}