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

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

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12"));
    try {//from  w  w  w .  j av a 2 s . c  o  m
        keyStore.load(instream, Constants.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.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 post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
        System.out.println("executing request" + post.getRequestLine());

        String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic";
        String nonce_str = Sha1Util.getNonceStr();
        String orderId = SUtils.getOrderId();
        String re_user_name = "?";
        String amount = "1";
        String desc = "";
        String spbill_create_ip = "123.56.102.224";

        String txt = TXT.replace("{mch_appid}", Constants.mch_appid);
        txt = txt.replace("{mchid}", Constants.mch_id);
        txt = txt.replace("{openid}", openid);
        txt = txt.replace("{nonce_str}", nonce_str);
        txt = txt.replace("{partner_trade_no}", orderId);
        txt = txt.replace("{check_name}", "FORCE_CHECK");
        txt = txt.replace("{re_user_name}", re_user_name);
        txt = txt.replace("{amount}", amount);
        txt = txt.replace("{desc}", desc);
        txt = txt.replace("{spbill_create_ip}", spbill_create_ip);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_appid", Constants.mch_appid);
        map.put("mchid", Constants.mch_id);
        map.put("openid", openid);
        map.put("nonce_str", nonce_str);
        map.put("partner_trade_no", orderId);
        //FORCE_CHECK| OPTION_CHECK | NO_CHECK
        map.put("check_name", "OPTION_CHECK");
        map.put("re_user_name", re_user_name);
        map.put("amount", amount);
        map.put("desc", desc);
        map.put("spbill_create_ip", spbill_create_ip);

        String sign = SUtils.createSign(map).toUpperCase();
        txt = txt.replace("{sign}", sign);

        post.setEntity(new StringEntity(txt, "utf-8"));

        CloseableHttpResponse response = httpclient.execute(post);
        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) {
                    sb.append(text);
                }
                String resp = sb.toString();
                LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp));
                if (isOk(resp)) {

                    String payment_no = getValue(resp, "payment_no");
                    LoggerUtils.getInstance()
                            .log(String.format("order %s pay OK   payment_no %s", orderId, payment_no));
                }

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

From source file:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {//from  w w w .  ja va 2 s  .  c  o  m
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
            
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }
    } finally {
    httpclient.close();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

From source file:com.yahoo.wiki.webservice.application.WikiMain.java

/**
 * Makes the dimensions passthrough./*from  ww w .  j a va2 s .  c  om*/
 * <p>
 * This method sends a lastUpdated date to each dimension in the dimension cache, allowing the health checks
 * to pass without having to set up a proper dimension loader. For each dimension, d, the following query is
 * sent to the /v1/cache/dimensions/d endpoint:
 * {
 *     "name": "d",
 *     "lastUpdated": "2016-01-01"
 * }
 *
 * @param port  The port through which we access the webservice
 *
 * @throws IOException If something goes terribly wrong when building the JSON or sending it
 */
private static void markDimensionCacheHealthy(int port) throws IOException {
    for (DimensionConfig dimensionConfig : new WikiDimensions().getAllDimensionConfigurations()) {
        String dimension = dimensionConfig.getApiName();
        HttpPost post = new HttpPost("http://localhost:" + port + "/v1/cache/dimensions/" + dimension);
        post.setHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(
                String.format("{\n \"name\":\"%s\",\n \"lastUpdated\":\"2016-01-01\"\n}", dimension)));
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = client.execute(post);
        LOG.debug("Mark Dimension Cache Updated Response: ", response);
    }
}

From source file:cn.org.once.cstack.utils.TestUtils.java

/**
 * Return the content of an URL.// w  w  w. ja  v  a 2  s .  c o  m
 *
 * @param url
 * @return
 * @throws ParseException
 * @throws IOException
 */
public static String getUrlContentPage(String url) throws ParseException, IOException {
    HttpGet request = new HttpGet(url);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    return EntityUtils.toString(entity);
}

From source file:com.vmware.content.samples.client.util.HttpUtil.java

/**
 * Downloads a file from a given HTTP URI in a given folder.
 *
 * @param uri HTTP URI to download file from.
 * @param folderToDownloadFiles path to a directory on the local storage
 *                              to store the download the files.
 * @param fileName name to use when creating the downloaded file on the local storage.
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 * @throws java.io.IOException/*from   w  w  w.jav  a  2  s  .c  om*/
 */
public static void downloadFileFromUri(URI uri, String folderToDownloadFiles, String fileName)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    HttpGet getRequest = new HttpGet(uri);
    CloseableHttpClient httpClient = getCloseableHttpClient();
    HttpResponse response = httpClient.execute(getRequest);
    File file = new File(folderToDownloadFiles, fileName);
    response.getEntity().writeTo(new FileOutputStream(file));
    IOUtil.print("Downloaded: " + file.getPath());
}

From source file:org.fcrepo.camel.indexing.solr.integration.TestUtils.java

public static InputStream httpGet(final String url) throws Exception {
    final CloseableHttpClient httpClient = HttpClients.createDefault();
    final HttpGet get = new HttpGet(url);
    return httpClient.execute(get).getEntity().getContent();
}

From source file:com.continuuity.loom.TestHelper.java

public static void finishTask(String loomUrl, FinishTaskRequest finishRequest) throws Exception {
    HttpPost httpPost = new HttpPost(String.format("%s/v1/loom/tasks/finish", loomUrl));
    httpPost.setEntity(new StringEntity(GSON.toJson(finishRequest)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {/*from w  ww .  jav a2  s.  c  o m*/
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        response.close();
    }
}

From source file:org.moneta.utils.RestTestingUtils.java

public static HttpResponse simpleRESTGet(String requestUri) {
    Validate.notEmpty(requestUri, "Null or blank requestUri not allowed.");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(requestUri);
    try {//from   www .j av a  2 s .com
        return httpclient.execute(httpGet);
    } catch (Exception e) {
        throw new ContextedRuntimeException(e).addContextValue("requestUri", requestUri);
    }
}

From source file:com.continuuity.loom.TestHelper.java

public static SchedulableTask takeTask(String loomUrl, TakeTaskRequest request) throws Exception {
    HttpPost httpPost = new HttpPost(String.format("%s/v1/loom/tasks/take", loomUrl));
    httpPost.setEntity(new StringEntity(GSON.toJson(request)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {//ww  w  .  jav  a  2s  .  c o  m
        Assert.assertEquals(2, response.getStatusLine().getStatusCode() / 100);
        if (response.getEntity() == null) {
            return null;
        }
        return GSON.fromJson(EntityUtils.toString(response.getEntity()), SchedulableTask.class);
    } finally {
        response.close();
    }
}

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);//from w  w w  . j av  a2 s  .c  o m

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}