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:org.springside.examples.schedule.TransferOaDataToGx.java

public static void main(String[] args) {
    //      /*w w  w  .jav  a2  s  .c  om*/
    //      // ?
    //      HttpPost httpPost = new HttpPost("http://gxoa.cc/login!login.do?userName=&userPassword=gxuser&loginState=1");
    //      
    //      // ?connection poolclient
    //      RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000)
    //            .setConnectTimeout(20 * 1000).build();
    //
    //      CloseableHttpClient  httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20)
    //            .setDefaultRequestConfig(requestConfig).build();
    //      try {
    //         CloseableHttpResponse  closeableHttpResponse = httpClient.execute(httpPost);
    //         System.out.println(IOUtils.toString(closeableHttpResponse.getEntity().getContent(), "UTF-8"));
    //         HttpGet httpGet = new HttpGet("http://gxoa.cc/attachmentDownload.do?filePath=2010-07/2010-07-28-4bdd9279-c09e-4b68-80fc-c9d049c6bdfc-GXTC-1005124--??20091062.rar");
    //         CloseableHttpResponse closeableHttpResponseFile = httpClient.execute(httpGet);
    //         //FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\"));
    //         System.out.println(IOUtils.toString(closeableHttpResponseFile.getEntity().getContent(), "UTF-8"));
    //
    //         
    //      } catch (ClientProtocolException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      } catch (IOException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }

    //      

    HttpPost httpPost = new HttpPost("http://219.239.33.123:9090/quickstart/api/getFileFromFTP");

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

    nvps.add(new BasicNameValuePair("filePath",
            "2015-04/2015-04-28-718f376f-b725-4e18-87e2-43e30124b2b5-GXTC-1506112-&-.rar"));

    String salt = "GXCX_OA_SALT";
    long currentTime = ((new Date().getTime() * 4 + 2) * 5 - 1) * 8 + 3;// by yucy
    String key = salt + currentTime;
    nvps.add(new BasicNameValuePair("key", Base64.encodeBase64String(key.getBytes())));

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // ?connection poolclient
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000)
            .setConnectTimeout(20 * 1000).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20)
            .setDefaultRequestConfig(requestConfig).build();
    try {
        CloseableHttpResponse closeableHttpResponseFile = httpClient.execute(httpPost);

        FileUtils.writeByteArrayToFile(new File("D:/upload/templateBulletin.rar"),
                IOUtils.toByteArray(closeableHttpResponseFile.getEntity().getContent()));
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //TODO  ?
    //FileUtils.writeByteArrayToFile( file, FileUtils.readFileToByteArray( new File("D:/upload/templateBulletin.zip") ) );

}

From source file:org.gzk.image.junit.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/apiclient_cert.p12"));
    try {//w w  w .jav  a 2  s.c  om
        keyStore.load(instream, "1374938902".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1374938902".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 {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            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;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

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

From source file:com.magicbeans.banjiuwan.util.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {//from ww  w . j  a va  2  s  .c om
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

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

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            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;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

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

From source file:com.wxpay.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert1.p12"));
    try {/*from www .  j ava 2  s  .  c o m*/
        keyStore.load(instream, "1269885501".toCharArray());
    } finally {
        instream.close();
    }

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

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            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;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

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

From source file:com.lxf.spider.client.QuickStart.java

public static void main(String[] args) throws Exception {
    InputStream input = null;//from  w ww .j  a  v  a  2 s . c  om
    OutputStream output = null;
    //httpclient
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //get
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/pdqx.jc.web/cen/center.html");
        //
        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 {
            //???
            int statusCode = response1.getStatusLine().getStatusCode();
            //??200?
            if (statusCode == HttpStatus.SC_OK) {
                //                  input = httpGet.getRequestLine();
                System.out.println(response1.getStatusLine());
                //
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                input = entity1.getContent();
                output = new FileOutputStream("d:/lxf.data");
                //?
                int tempByte = -1;
                while ((tempByte = input.read()) > 0) {
                    output.write(tempByte);
                }
                EntityUtils.consume(entity1);
                //?
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }

        } finally {
            response1.close();
        }

        /*HttpPost httpPost = new HttpPost("http://targethost/login");
        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();
    }
}

From source file:com.mycompany.horus.Teste.java

public static void main(String[] args) throws Exception {

    ServiceListener list = new ServiceListener();
    list.getHorusServicesList();//from  ww w.  j a  v a  2s . c  om

    String soapBody = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:est=\"http://servicos.saude.gov.br/horus/v1r0/EstoqueService\">\n"
            + " <soap:Header>\n"
            + " <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wsswssecurity-secext-1.0.xsd\">\n"
            + " <wsse:UsernameToken wsu:Id=\"Id-0001334008436683-000000002c4a1908-1\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n"
            + " <wsse:Username>HORUS</wsse:Username>\n"
            + " <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wssusername-token-profile-1.0#PasswordText\">SENHA</wsse:Password>\n"
            + " </wsse:UsernameToken>\n" + " </wsse:Security>\n" + " </soap:Header>\n"
            + " <soap:Body><est:requestConsultarPosicaoEstoquePorCNES>\n" + " <est:cnes>7604041</est:cnes>\n"
            + " </est:requestConsultarPosicaoEstoquePorCNES>\n" + " </soap:Body>\n" + "</soap:Envelope>\n";
    try {
        // Get target URL

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        StringEntity strEntity = new StringEntity(soapBody, "UTF-8");
        strEntity.setContentType("text/xml");
        HttpPost post = new HttpPost("https://servicos.saude.gov.br/horus/v1r0/EstoqueService");
        post.setEntity(strEntity);

        // Execute request
        HttpResponse response = httpclient.execute(post);
        HttpEntity respEntity = response.getEntity();
        String resp = EntityUtils.toString(respEntity);
        if (respEntity != null) {
            System.out.println("Response:");
            System.out.println(resp);
            //Changing response to Xml file
            stringToDom(resp);

        } else {
            System.out.println("No Response");
        }
    } catch (Exception e) {
        System.out.println("Other exception = " + e.toString());
    }
}

From source file:interoperabilite.webservice.client.ClientCustomPublicSuffixList.java

public final static void main(String[] args) throws Exception {

    // Use PublicSuffixMatcherLoader to load public suffix list from a file,
    // resource or from an arbitrary URL
    PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
            .load(new URL("https://publicsuffix.org/list/effective_tld_names.dat"));

    // Please use the publicsuffix.org URL to download the list no more than once per day !!!
    // Please consider making a local copy !!!

    DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);

    RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
    Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
            .register(CookieSpecs.DEFAULT, cookieSpecProvider)
            .register(CookieSpecs.STANDARD, cookieSpecProvider)
            .register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider).build();

    CloseableHttpClient httpclient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier)
            .setDefaultCookieSpecRegistry(cookieSpecRegistry).build();
    try {/*from   w ww  . j  ava  2  s .  c o m*/

        HttpGet httpget = new HttpGet("https://httpbin.org/");

        System.out.println("executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:isc_415_practica_1.ISC_415_Practica_1.java

/**
 * @param args the command line arguments
 *///from w  ww .j a v a  2s .c o  m
public static void main(String[] args) {
    String urlString;
    Scanner input = new Scanner(System.in);
    Document doc;

    try {
        urlString = input.next();
        if (urlString.equals("servlet")) {
            urlString = "http://localhost:8084/ISC_415_Practica1_Servlet/client";
        }
        urlString = urlString.contains("http://") || urlString.contains("https://") ? urlString
                : "http://" + urlString;
        doc = Jsoup.connect(urlString).get();
    } catch (Exception ex) {
        System.out.println("El URL ingresado no es valido.");
        return;
    }

    ArrayList<NameValuePair> formInputParams;
    formInputParams = new ArrayList<>();
    String[] plainTextDoc = new TextNode(doc.html(), "").getWholeText().split("\n");
    System.out.println(String.format("Nmero de lineas del documento: %d", plainTextDoc.length));
    System.out.println(String.format("Nmero de p tags: %d", doc.select("p").size()));
    System.out.println(String.format("Nmero de img tags: %d", doc.select("img").size()));
    System.out.println(String.format("Nmero de form tags: %d", doc.select("form").size()));

    Integer index = 1;

    ArrayList<NameValuePair> urlParameters = new ArrayList<>();
    for (Element e : doc.select("form")) {
        System.out.println(String.format("Form %d: Nmero de Input tags %d", index, e.select("input").size()));
        System.out.println(e.select("input"));

        for (Element formInput : e.select("input")) {
            if (formInput.attr("id") != null && formInput.attr("id") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("id"), "PRACTICA1"));
            } else if (formInput.attr("name") != null && formInput.attr("name") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("name"), "PRACTICA1"));
            }
        }

        index++;
    }

    if (!urlParameters.isEmpty()) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, Consts.UTF_8);
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
        } catch (IOException ex) {
            Logger.getLogger(ISC_415_Practica_1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:testing01.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String outputFile = "test.html";
    String baseWebSite = "http://www.ettoday.net/news/20130802/250478.htm";
    try {/*  w w  w  . ja  va2  s  .c  o  m*/
        //HttpGet httpGet = new HttpGet(baseWebSite + "cat/politic/r");
        HttpGet httpGet = new HttpGet(baseWebSite);
        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
            String responseString = EntityUtils.toString(entity1, "UTF-8");
            // System.out.println(responseString);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
            out.write(responseString);
            out.close();
            EntityUtils.consume(entity1);
            System.out.println(baseWebSite + " output to " + outputFile + " successful");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            response1.close();
        }
        /*
         * HttpPost httpPost = new HttpPost("http://targethost/login"); 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();
    }
}

From source file:jdbc.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    java.net.CookieManager cm = new java.net.CookieManager();
    java.net.CookieHandler.setDefault(cm);

    try {//w  w  w  . ja va2s. co  m
        HttpGet httpget = new HttpGet("http://www.cophieu68.vn/export/excel.php?id=AAA");
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("http://www.cophieu68.vn/export/excel.php?id=AAA"))
                .addParameter("username", "hello_nguyenson@live.com").addParameter("tpassword", "19931994")
                .build();
        CloseableHttpResponse response2 = httpclient.execute(login);

        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form get: " + response2.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();

            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }

        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}