List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:interoperabilite.webservice.client.ClientEvictExpiredConnections.java
public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(100);/*from ww w . j av a 2s . c om*/ CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections() .evictIdleConnections(5L, TimeUnit.SECONDS).build(); try { // create an array of URIs to perform GETs on String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", }; for (int i = 0; i < urisToGet.length; i++) { String requestURI = urisToGet[i]; HttpGet request = new HttpGet(requestURI); System.out.println("Executing request " + requestURI); CloseableHttpResponse response = httpclient.execute(request); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } PoolStats stats1 = cm.getTotalStats(); System.out.println("Connections kept alive: " + stats1.getAvailable()); // Sleep 10 sec and let the connection evictor do its job Thread.sleep(10000); PoolStats stats2 = cm.getTotalStats(); System.out.println("Connections kept alive: " + stats2.getAvailable()); } finally { httpclient.close(); } }
From source file:com.orange.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//w w w. j a v a2 s. c o 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.ClientPreemptiveBasicAuthentication.java
public static void main(String[] args) throws Exception { HttpHost target = new HttpHost("localhost", 80, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//w w w . j a va 2 s . c om // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpGet httpget = new HttpGet("/"); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); for (int i = 0; i < 3; i++) { CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } } finally { httpclient.close(); } }
From source file:org.springside.examples.schedule.TransferOaDataToGx.java
public static void main(String[] args) { // // www . j av a2 s. c o m // // ? // 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:com.lxf.spider.client.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/* w ww.j av a 2s.c om*/ 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(); } }
From source file:com.zhch.example.commons.http.v4_5.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {// ww w . ja v a 2 s . c o 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) { 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(); } }
From source file:com.lxf.spider.client.ClientPreemptiveDigestAuthentication.java
public static void main(String[] args) throws Exception { HttpHost target = new HttpHost("localhost", 80, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/*from w ww. j a v a 2s .com*/ // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local // auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(target, digestAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpGet httpget = new HttpGet("/"); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); for (int i = 0; i < 3; i++) { CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } } finally { httpclient.close(); } }
From source file:com.ccreservoirs.RSSReader.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {// ww w . j a v a 2 s . co m HttpGet httpget = new HttpGet("http://blog.csdn.net/rss.html?type=Home&channel="); 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(); } }
From source file:com.lxf.spider.client.ClientEvictExpiredConnections.java
public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(100);/* w ww. j av a2s.c o m*/ CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build(); try { // create an array of URIs to perform GETs on String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", }; IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); connEvictor.start(); for (int i = 0; i < urisToGet.length; i++) { String requestURI = urisToGet[i]; HttpGet request = new HttpGet(requestURI); System.out.println("Executing request " + requestURI); CloseableHttpResponse response = httpclient.execute(request); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } // Sleep 10 sec and let the connection evictor do its job Thread.sleep(20000); // Shut down the evictor thread connEvictor.shutdown(); connEvictor.join(); } finally { httpclient.close(); } }
From source file:com.gemini.httpclienttest.HttpClientTestMain.java
public static void main(String[] args) { //authenticate with the server URL url;/*from w w w . j av a 2s.co m*/ try { url = new URL("http://198.11.209.34:5000/v2.0/tokens"); } catch (MalformedURLException ex) { System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0"); return; } CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try { HttpPost httpPost = new HttpPost(url.toString()); httpPost.setHeader("Content-Type", "application/json"); StringEntity strEntity = new StringEntity( "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}"); httpPost.setEntity(strEntity); //System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); try { //get the response status code String respStatus = response.getStatusLine().getReasonPhrase(); //get the response body int bytes = response.getEntity().getContent().available(); InputStream body = response.getEntity().getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(body)); String line; StringBuffer sbJSON = new StringBuffer(); while ((line = in.readLine()) != null) { sbJSON.append(line); } String json = sbJSON.toString(); EntityUtils.consume(response.getEntity()); GsonBuilder gsonBuilder = new GsonBuilder(); Object parsedJson = gsonBuilder.create().fromJson(json, Object.class); System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString()); if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) { com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson; if (treeJson.containsKey("id")) { String s = (String) treeJson.getOrDefault("id", "no key provided"); System.out.printf("\n\ntree contained id %s\n", s); } else { System.out.printf("\n\ntree does not contain key id\n"); } } } catch (IOException ex) { System.out.print(ex); } finally { response.close(); } } catch (IOException ex) { System.out.print(ex); } finally { //lots of exceptions, just the connection and exit try { httpclient.close(); } catch (IOException | NoSuchMethodError ex) { System.out.print(ex); return; } } }