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

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

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:org.syncany.plugins.php.PhpTransferManager.java

private int operate(String action, IPost mutator) throws Exception {
    String url = settings.getField("url") + "/syncany_php.php";
    String context = settings.getField("context");
    String userid = settings.getField("userid");
    String passwd = settings.getField("passwd");

    logger.info("url: " + url);
    logger.info("action: " + action);
    logger.info("userid: " + userid + ", context: " + context);
    lastSite = url;//from   w w w .  j  av  a 2s . c  o  m

    HttpPost p = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("userid", userid));
    nvps.add(new BasicNameValuePair("passwd", passwd));
    nvps.add(new BasicNameValuePair("context", context));
    nvps.add(new BasicNameValuePair("action", action));
    mutator.mutateNVPS(nvps);
    p.setEntity(new UrlEncodedFormEntity(nvps));

    int maxlen = mutator.mutatePost(p);
    int responsecode = -1;

    try {
        CloseableHttpClient httpclient = getHttpClient(); //HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(p);
        HttpEntity e = response.getEntity();
        long len = e.getContentLength();
        logger.info("length of response: " + len);
        StatusLine sl = response.getStatusLine();
        int code = sl.getStatusCode();
        if (code != 200) {
            response.close();
            httpclient.close();
            throw new Exception("Response on http call: " + code);
        } else {
            if ((maxlen >= 0) && ((len >= maxlen) || (len < 0))) {
                response.close();
                httpclient.close();
                throw new Exception("Expected maximum length: " + maxlen + ", returned content length: " + len);
            } else {
                try {
                    InputStream b = e.getContent();
                    responsecode = mutator.consumeResponse(b);
                    b.close();
                    response.close();
                    httpclient.close();
                } catch (Exception ex) {
                    response.close();
                    httpclient.close();
                    throw new Exception(ex);
                }
            }
        }
        response.close();
        httpclient.close();
    } catch (Exception e) {
        throw new Exception(e);
    }
    return responsecode;
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, String payload,
        HashMap<String, String> headers) {
    HttpPost post = null;//  w  w  w  .ja  v  a2 s.  c o  m
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        post = new HttpPost(url);
        post.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }

        post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        response = httpclient.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

public String doUpload(String url, File uploadFile) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {//from  w  w w .j  av a 2 s .co  m
        _LOG.debug("Upload File [" + uploadFile + "]");
        String _result = EntityUtils
                .toString(_httpClient
                        .execute(RequestBuilder.post().setUri(url)
                                .setEntity(MultipartEntityBuilder.create()
                                        .addPart("media", new FileBody(uploadFile)).build())
                                .build())
                        .getEntity(), DEFAULT_CHARSET);
        _LOG.debug("Upload File [" + uploadFile + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpPost(String url, List<NameValuePair> params) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w w  w .  j  a  v  a2s.  co  m
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        httppost.setHeader("accept", "application/json");
        CloseableHttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(br);
        return je.getAsJsonObject();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return null;
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public CloseableHttpResponse doGet(String url, String[] replaceParams, String[] params) {
    CloseableHttpResponse result = null;
    CloseableHttpClient client = null;
    try {/*from w w  w  . j  a  va2  s . c  o m*/
        if (replaceParams.length > 0) {
            for (int i = 0; i < replaceParams.length; i++) {
                url = url.replaceAll(replaceParams[i], params[i]);
            }
        }

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "url {0} ", url);

        HttpGet getMethod = new HttpGet(url);

        result = client.execute(getMethod);
        client.close();

    } catch (IOException ex) {
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
    Logger.getLogger(this.getClass().getName()).log(Level.INFO, "result {0} ", result.getEntity());

    return result;
}

From source file:com.foundationdb.server.service.security.RestSecurityIT.java

@Test
public void restAddDropUser() throws Exception {
    SecurityService securityService = securityService();
    assertNull(securityService.getUser("user3"));
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(getRestURL("/security/users", null, "akiban:topsecret"));
    post.setEntity(new StringEntity(ADD_USER, ContentType.APPLICATION_JSON));
    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();
    String content = EntityUtils.toString(response.getEntity());
    assertEquals(HttpStatus.SC_OK, code);
    assertNotNull(securityService.getUser("user3"));

    // Check returned id
    JsonNode idNode = readTree(content).get("id");
    assertNotNull("Has id field", idNode);
    assertEquals("id is integer", true, idNode.isInt());

    HttpDelete delete = new HttpDelete(getRestURL("/security/users/user3", null, "akiban:topsecret"));
    response = client.execute(delete);// w  ww.j  a  v  a  2s  .c  o m
    code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    client.close();
    assertEquals(HttpStatus.SC_OK, code);
    assertNull(securityService.getUser("user3"));
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Upload metadata file./*from  w  w  w. j  av a2 s.c o m*/
 *
 * @param endPoint the end point
 * @param xml the xml
 * @param client the client (optional)
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException the JSON exception
 */
private static String uploadMetadataFile(String endPoint, InputStream xml, CloseableHttpClient client)
        throws IOException, JSONException {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpPost request = new HttpPost(endPoint + TestObjects_URL + "?action=upload");

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("fileupload", xml, ContentType.TEXT_XML, "file.xml");
        HttpEntity entity = builder.build();

        request.setEntity(entity);

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);
            JSONObject jsonRoot = new JSONObject(body);
            return jsonRoot.getJSONObject("testObject").getString("id");
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestObjects_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:org.keycloak.testsuite.AssertEvents.java

private EventRepresentation fetchNextEvent() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from w ww  .java  2 s  .  co m*/
        HttpPost post = new HttpPost(defaultEventsQueueUri + "/event-queue");
        CloseableHttpResponse response = httpclient.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to retrieve event from " + post.getURI() + ": "
                    + response.getStatusLine().toString() + " / "
                    + IOUtils.toString(response.getEntity().getContent()));
        }

        return JsonSerialization.readValue(response.getEntity().getContent(), EventRepresentation.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public CloseableHttpResponse doPost(String url, String[] replaceParams, String[] params) {
    CloseableHttpResponse result = null;
    CloseableHttpClient client = null;
    try {/*from   w  ww  . j a  va2 s .  co m*/
        if (replaceParams.length > 0) {
            for (int i = 0; i < replaceParams.length; i++) {
                url = url.replaceAll(replaceParams[i], params[i]);
            }
        }

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "url {0} ", url);

        HttpPost postMethod = new HttpPost(url);

        result = client.execute(postMethod);
        client.close();

    } catch (IOException ex) {
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
    Logger.getLogger(this.getClass().getName()).log(Level.INFO, "result {0} ", result.getEntity());

    return result;
}

From source file:org.winardiaris.uangku.getDataURL.java

String getData(String url) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w  w  w . j a v  a  2s  .c  om*/
        HttpGet httpget = new HttpGet(url);
        System.out.println("Executing request " + httpget.getRequestLine());

        ResponseHandler<String> responseHandler;
        responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };

        String responseURL = httpclient.execute(httpget, responseHandler);
        return responseURL;
    } finally {
        httpclient.close();
    }
}