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:com.portfolio.data.utils.PostForm.java

public static boolean updateResource(String sessionid, String backend, String uuid, String lang, String json)
        throws Exception {
    /// Parse and create xml from JSON
    JSONObject files = (JSONObject) JSONValue.parse(json);
    JSONArray array = (JSONArray) files.get("files");

    if ("".equals(lang) || lang == null)
        lang = "fr";

    JSONObject obj = (JSONObject) array.get(0);
    String ressource = "";
    String attLang = " lang=\"" + lang + "\"";
    ressource += "<asmResource>" + "<filename" + attLang + ">" + obj.get("name") + "</filename>" + // filename
            "<size" + attLang + ">" + obj.get("size") + "</size>" + "<type" + attLang + ">" + obj.get("type")
            + "</type>" +
            //      obj.get("url");   // Backend source, when there is multiple backend
            "<fileid" + attLang + ">" + obj.get("fileid") + "</fileid>" + "</asmResource>";

    /// Send data to resource
    /// Server + "/resources/resource/file/" + uuid +"?lang="+ lang
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// ww w . ja v a  2s .c o  m
        HttpPut put = new HttpPut("http://" + backend + "/rest/api/resources/resource/" + uuid);
        put.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us

        StringEntity se = new StringEntity(ressource);
        se.setContentEncoding("application/xml");
        put.setEntity(se);

        CloseableHttpResponse response = httpclient.execute(put);

        try {
            HttpEntity resEntity = response.getEntity();
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    return false;
}

From source file:com.zhch.example.commons.http.v4_5.ClientExecuteProxy.java

public static void proxyExample() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w  w  w.j av a 2  s. c om
        HttpHost proxy = new HttpHost("24.157.37.61", 8080, "http");

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("http://www.ip.cn");
        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");

        request.setConfig(config);

        System.out.println(
                "Executing request " + request.getRequestLine() + " to " + request.getURI() + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity(), "utf8"));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java

/**
 * Invoke Business Rules with JSON content
 *
 * @param content The payload of itineraries to send to Business Rules.
 * @return A JSON string representing the output of Business Rules.
 *///from  ww  w  .j  av  a2 s .c o  m
public static String invokeRulesService(String json) throws Exception {
    PropertiesReader constants = PropertiesReader.getInstance();
    String username = constants.getStringProperty(USERNAME_KEY);
    String password = constants.getStringProperty(PASSWORD_KEY);
    String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY)
            + constants.getStringProperty(RULE_APP_PATH_KEY);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();

    String responseString = "";

    try {
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING);
        httpPost.setEntity(jsonEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, MessageUtils.ENCODING);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
    return responseString;
}

From source file:com.farsunset.cim.util.MessageDispatcher.java

private static String httpPost(String url, Message msg) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    nvps.add(new BasicNameValuePair("mid", msg.getMid()));
    nvps.add(new BasicNameValuePair("extra", msg.getExtra()));
    nvps.add(new BasicNameValuePair("action", msg.getAction()));
    nvps.add(new BasicNameValuePair("title", msg.getTitle()));
    nvps.add(new BasicNameValuePair("content", msg.getContent()));
    nvps.add(new BasicNameValuePair("sender", msg.getSender()));
    nvps.add(new BasicNameValuePair("receiver", msg.getReceiver()));
    nvps.add(new BasicNameValuePair("timestamp", String.valueOf(msg.getTimestamp())));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
    String data = null;/*from ww w.java 2s . c o m*/
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        data = EntityUtils.toString(entity2);
    } finally {
        response2.close();
    }

    return data;
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * ??//from w  w w  .  j  a v  a2  s  . c o  m
 *
 * @param uri
 * @param params
 * @return
 */
public static String post(String uri, String params) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    StringEntity stringEntity = new StringEntity(params, CHARSET.toString());
    httpPost.setEntity(stringEntity);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            httpResponse.close();
            return EntityUtils.toString(httpResponse.getEntity(), CHARSET);
        }
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:com.comcast.viper.hlsparserj.PlaylistFactory.java

/**
 * Returns a playlist inputStream given an httpClient and a URL.
 * @param httpClient http client// w ww  .ja  v  a  2  s. c  om
 * @param url URL to a playlist
 * @return inputStream
 * @throws IOException on HTTP connection exception
 */
private static InputStream getPlaylistInputStream(final CloseableHttpClient httpClient, final URL url)
        throws IOException {
    HttpGet get = new HttpGet(url.toString());
    CloseableHttpResponse response = null;
    response = httpClient.execute(get);
    if (response == null) {
        throw new IOException("Request returned a null response");
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        response.close();
        throw new IOException("Request returned a status code of " + response.getStatusLine().getStatusCode());
    }

    return response.getEntity().getContent();
}

From source file:org.apache.ofbiz.solr.SolrUtil.java

public static HttpSolrClient getHttpSolrClient(String solrIndexName)
        throws ClientProtocolException, IOException {
    HttpClientContext httpContext = HttpClientContext.create();

    CloseableHttpClient httpClient = null;
    if (trustSelfSignedCert) {
        httpClient = UtilHttp.getAllowAllHttpClient();
    } else {//  ww w  . ja  v  a 2 s.c o m
        httpClient = HttpClients.createDefault();
    }

    RequestConfig requestConfig = null;
    if (UtilValidate.isNotEmpty(socketTimeout) && UtilValidate.isNotEmpty(connectionTimeout)) {
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectionTimeout).setRedirectsEnabled(true).build();
    } else if (UtilValidate.isNotEmpty(socketTimeout)) {
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setRedirectsEnabled(true)
                .build();
    } else if (UtilValidate.isNotEmpty(connectionTimeout)) {
        requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout).setRedirectsEnabled(true)
                .build();
    } else {
        requestConfig = RequestConfig.custom().setRedirectsEnabled(true).build();
    }

    HttpGet httpLogin = new HttpGet(
            solrUrl + "/control/login?USERNAME=" + clientUsername + "&PASSWORD=" + clientPassword);
    httpLogin.setConfig(requestConfig);
    CloseableHttpResponse loginResponse = httpClient.execute(httpLogin, httpContext);
    loginResponse.close();
    return new HttpSolrClient(solrUrl + "/" + solrIndexName, httpClient);
}

From source file:nayan.netty.client.FileUploadClient.java

private static void uploadFile() throws Exception {
    File file = new File("small.jpg");

    HttpEntity httpEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", file, ContentType.create("image/jpeg"), file.getName()).build();

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://localhost:8080");

    httppost.setEntity(httpEntity);/*www.j  a  v a  2s .c  om*/
    System.out.println("executing request " + httppost.getRequestLine());

    CloseableHttpResponse response = httpclient.execute(httppost);

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null) {
        System.out.println("Response content length: " + resEntity.getContentLength());
    }

    EntityUtils.consume(resEntity);

    response.close();
}

From source file:com.deying.util.weixin.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    System.out.println("111111111111111111111111111111111111111111111118 ");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert.p12"));//P12
    try {/*w  ww  . j a va2 s. co  m*/
        keyStore.load(instream, "1233374102".toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1233374102".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(url); // ??
        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();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.huotu.mallduobao.common.thirdparty.ClientCustomSSL.java

public static String doRefund(String url, String data, String celPath, String celPassword) throws Exception {
    /**// w  w  w .  java2s .  c  om
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(celPath));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, celPassword.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, celPassword.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(url); // ??
        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();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}