Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse 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:tradeok.HttpTool.java

@SuppressWarnings("deprecation")
public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout)
        throws Exception {
    String responseString = null;
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout)
            .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();

    StringBuilder sb = new StringBuilder();
    sb.append(url);/*from w w w  .ja  v a2  s.c o  m*/
    int i = 0;
    if (params != null) {
        for (Entry<String, String> entry : params.entrySet()) {
            if (i == 0 && !url.contains("?")) {
                sb.append("?");
            } else {
                sb.append("&");
            }
            sb.append(entry.getKey());
            sb.append("=");
            String value = entry.getValue();
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.out.printf("\nwarn:encode http get params error, value is " + value, e);
                sb.append(URLEncoder.encode(value));
            }
            i++;
        }
    }
    //        System.out.printf("\ninfo:[HttpUtils Get] begin invoke:"
    //                + sb.toString());
    HttpGet get = new HttpGet(sb.toString());
    get.setConfig(requestConfig);
    get.setHeader("Connection", "keep-alive");

    try {
        CloseableHttpResponse response = httpclient.execute(get);
        try {
            HttpEntity entity = response.getEntity();
            try {
                if (entity != null) {
                    responseString = EntityUtils.toString(entity, encode);
                }
            } finally {
                if (entity != null) {
                    entity.getContent().close();
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } finally {
        get.releaseConnection();
    }
    return responseString;
}

From source file:com.networknt.light.server.handler.loader.Loader.java

public static void login(String host, String userId, String password) throws Exception {
    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "user");
    inputMap.put("name", "signInUser");
    inputMap.put("readOnly", false);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("userIdEmail", userId);
    data.put("password", password);
    data.put("rememberMe", true);
    data.put("clientId", "example@Browser");
    inputMap.put("data", data);

    HttpPost httpPost = new HttpPost(host + "/api/rs");
    StringEntity input = new StringEntity(
            ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
    input.setContentType("application/json");
    httpPost.setEntity(input);//from ww w. j  a v a2s. c  om
    CloseableHttpResponse response = httpclient.execute(httpPost);

    try {

        //System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        //System.out.println("json = " + json);
        Map<String, Object> jsonMap = ServiceLocator.getInstance().getMapper().readValue(json,
                new TypeReference<HashMap<String, Object>>() {
                });
        jwt = (String) jsonMap.get("accessToken");
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        response.close();
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

private static void closeResponse(CloseableHttpResponse formResponse) {
    if (formResponse != null) {
        try {//www.jav a  2 s.  c o  m
            formResponse.close();
        } catch (IOException e) {
            // we don't care we are logged in or are throwing an exception for a different problem
            LOGGER.log(Level.FINER, "Failed to close response", e);
        }
    }
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do get.//  w w  w . ja  va  2  s . c om
 *
 * @param uri
 *            the uri
 * @param headers
 *            the headers
 * @return the string
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws HttpResponseException
 *             the http response exception
 */
public static HttpGetSimpleResp doGet(String uri, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGetSimpleResp resp = new HttpGetSimpleResp();
    try {
        HttpGet httpGet = new HttpGet(uri);
        for (String key : headers.keySet()) {
            httpGet.addHeader(key, headers.get(key));
        }
        CloseableHttpResponse response = httpclient.execute(httpGet);
        resp.setStatusCode(response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // TODO to use for performance in the future
                    // ResponseHandler<String> handler = new BasicResponseHandler();
                    resp.setResult(new BasicResponseHandler().handleResponse(response));
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            // TODO optimiz (repeating code)
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

From source file:tradeok.HttpTool.java

public static String postJsonBody(String url, int timeout, Map<String, Object> map, String encoding)
        throws Exception {
    HttpPost post = new HttpPost(url);
    try {/*from   w  w w .  ja  v  a2  s  . c  om*/
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setExpectContinueEnabled(false)
                .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        post.setConfig(requestConfig);
        post.setHeader("User-Agent", USER_AGENT);
        post.setHeader("Accept",
                "text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        String str1 = object2json(map).replace("\\", "");
        post.setEntity(new StringEntity(str1, encoding));
        CloseableHttpResponse response = httpclient.execute(post);
        try {
            HttpEntity entity = response.getEntity();
            try {
                if (entity != null) {
                    String str = EntityUtils.toString(entity, encoding);
                    return str;
                }
            } finally {
                if (entity != null) {
                    entity.getContent().close();
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } finally {
        post.releaseConnection();
    }
    return "";
}

From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (HiredJudge j : doc.getHiredJudges()) {
            ids.add(j.getId());/*from w  w  w.jav a  2  s  .  c o m*/
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITJudgeController.delete();
}

From source file:org.wuspba.ctams.ws.ITBandMemberController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (BandMember m : doc.getBandMembers()) {
            ids.add(m.getId());// w w w .ja va  2s  .  c om
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITPersonController.delete();
}

From source file:org.wuspba.ctams.ws.ITVenueController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (Venue v : doc.getVenues()) {
            ids.add(v.getId());/*from w w  w.  j a  va2  s .  com*/
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }
}

From source file:com.bbc.util.ClientCustomSSL.java

public static String clientCustomSLL(String mchid, String path, String data) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    System.out.println("?...");
    FileInputStream instream = new FileInputStream(new File("/payment/apiclient_cert.p12"));
    try {/*from   ww w .j  a  va  2  s  .c  o m*/
        keyStore.load(instream, mchid.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httpost = new HttpPost(path);
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer("");
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                    sb.append(text);
                }
                return sb.toString();

            }
            EntityUtils.consume(entity);
            return "";
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the POST way.</p>
 * /* ww w. j  a va 2s .  co  m*/
 * @param url      request URI
 * @param json      request parameter(json format string)
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String post(String url, String json, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    String result = null;
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;

    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "text/plain");
        httpPost.setEntity(new StringEntity(json, "UTF-8"));

        httpResponse = httpClient.execute(httpPost);

        HttpEntity entity = httpResponse.getEntity();

        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("POST?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}