List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:demo.example.ClientAbortMethod.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from www.ja v a2s. c om*/ HttpGet httpget = new HttpGet("http://httpbin.org/get"); System.out.println("Executing request " + httpget.getURI()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Do not feel like reading the response body // Call abort on the request object httpget.abort(); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:myexamples.QuickStart.java
public static void main(String[] args) throws Exception { Gson gson = new Gson(); CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from ww w . ja v a 2 s .co m HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9"); 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 if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < 2048) { System.out.println(EntityUtils.toString(entity1)); } else { System.out.println("entity length=" + len); } } EntityUtils.consume(entity1); } 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.sim.demo.httpclient.httpget.SinaDemo.java
public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); // HttpGet/*from w w w . j av a 2 s . c o m*/ HttpGet httpGet = new HttpGet("http://www.sina.com"); System.out.println("executing request " + httpGet.getURI()); // get HttpResponse response = httpClient.execute(httpGet); // ?? HttpEntity entity = response.getEntity(); // ??? System.out.println(response.getStatusLine()); if (entity != null) { // ?? System.out.println("Response content lenght:" + entity.getContentLength()); String content = EntityUtils.toString(entity, "UTF-8").trim(); // HttpClient?? String? System.out.println("Response content:" + content); } // ? httpClient.close(); }
From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuthFormatURL.java
public static void main(String[] args) { // TODO code application logic here Map<String, String> params = new HashMap<String, String>(); params.put("host", "10.49.28.3"); params.put("port", "8081"); params.put("reportName", "vencimientos"); params.put("parametros", "feini=2016-09-30&fefin=2016-09-30"); StrSubstitutor sub = new StrSubstitutor(params, "{", "}"); String urlTemplate = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{parametros}"; String url = sub.replace(urlTemplate); try {/* www. jav a 2s. co m*/ CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jasperadmin", "jasperadmin")); CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/pdf"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("vencimientos.pdf")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); if (Desktop.isDesktopSupported()) { File pdfFile = new File("vencimientos.pdf"); Desktop.getDesktop().open(pdfFile); } } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java
public static void main(String[] args) { // TODO code application logic here String host = "10.49.28.3"; String port = "8081"; String reportName = "vencimientos"; String params = "feini=2016-09-30&fefin=2016-09-30"; String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}"; url = url.replace("{host}", host); url = url.replace("{port}", port); url = url.replace("{reportName}", reportName); url = url.replace("{params}", params); try {//from w w w . j a va 2 s. co m CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password")); CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/pdf"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("vencimientos.pdf")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); if (Desktop.isDesktopSupported()) { File pdfFile = new File("vencimientos.pdf"); Desktop.getDesktop().open(pdfFile); } } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:zz.pseas.ghost.login.weibo.WeibocnLogin.java
public static void main(String[] args) throws NullPointerException { // ?URL/*from w w w .j a v a 2 s.c o m*/ String Loginurl = "http://login.weibo.cn/login/"; String firstpage = "http://weibo.cn/?vt=4"; // ?? String loginnum = "test"; String loginpwd = "test"; CloseableHttpClient httpclient = HttpClients.createDefault(); // HttpGet httpget = new HttpGet(Loginurl); try { CloseableHttpResponse response = httpclient.execute(httpget); String responhtml = null; try { responhtml = EntityUtils.toString(response.getEntity()); // System.out.println(responhtml); } catch (IOException e1) { e1.printStackTrace(); } // vk?,splithtml,?? String vk = responhtml.split("<input type=\"hidden\" name=\"vk\" value=\"")[1].split("\" /><input")[0]; System.out.println(vk); String pass = vk.split("_")[0]; String finalpass = "password_" + pass; System.out.println(finalpass); response.close(); List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); pairs.add(new BasicNameValuePair("mobile", loginnum)); pairs.add(new BasicNameValuePair(finalpass, loginpwd)); pairs.add(new BasicNameValuePair("remember", "on")); pairs.add(new BasicNameValuePair("vk", vk)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8); // HttpPost httppost = new HttpPost(Loginurl); httppost.setEntity(entity); // ??? CloseableHttpResponse response2 = httpclient.execute(httppost); System.out.println(response2.getStatusLine().toString()); httpclient.execute(httppost); // ? System.out.println("success"); HttpGet getinfo = new HttpGet("http://m.weibo.cn/p/100803?vt=4"); CloseableHttpResponse res; res = httpclient.execute(getinfo); System.out.println("??:"); // ?html System.out.println(EntityUtils.toString(res.getEntity())); res.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:cn.anthony.util.ClientFormLogin.java
public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); try {//from www . j a v a 2 s. c o m HttpGet httpget = new HttpGet("https://someportal/"); 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("https://someportal/")) .addParameter("IDToken1", "username").addParameter("IDToken2", "password").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(); } }
From source file:com.client.SoapClientApache.java
public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w .j av a2s . c om HttpGet httpGet = new HttpGet("http://google.com/"); 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 either fully consume the response content or abort request // execution by calling CloseableHttpResponse#close(). try { System.out.println("Response for http get"); 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(); } File file = new File("temConvertRq.xml"); File fileOutXml = new File("temConvertRs.xml"); fileOutXml.createNewFile(); System.out.println("Before file entity"); FileEntity entity = new FileEntity(file, ContentType.create("text/xml", "UTF-8")); System.out.println("Before http post"); HttpPost httpPost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx"); httpPost.setEntity(entity); System.out.println("Entity set"); //Add headers httpPost.addHeader("SOAPAction", "http://www.w3schools.com/webservices/CelsiusToFahrenheit"); httpPost.addHeader("Host", "www.w3schools.com"); httpPost.addHeader("Content-Type", "text/xml; charset=utf-8"); //httpPost.addHeader("Content-Length", "length"); System.out.println("after headers added"); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println("before getting the response status"); System.out.println("Response Status= " + response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); String outXml = EntityUtils.toString(entity2); System.out.println("XMl Response!!!!!!!!! = " + outXml); // entity2.writeTo(System.out); //System.out.println("R // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); FileUtils.writeStringToFile(fileOutXml, outXml, "UTF-8"); } finally { response2.close(); } } finally { httpclient.close(); } }
From source file:com.orange.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from w w w . j a v a 2 s. co m*/ HttpGet httpget = new HttpGet("http://httpbin.org/get"); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { mRead(entity); } } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.lxf.spider.client.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from ww w. j a v a 2 s .c o m*/ HttpGet httpget = new HttpGet("http://localhost/"); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent(); try { instream.read(); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection release instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); } }