List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:com.zxy.commons.httpclient.HttpclientUtils.java
/** * url?byte[]/*from w ww .j a va2 s . c o m*/ * * @param connectTimeoutSec () * @param socketTimeoutSec ??() * @param url url? * @return byte[] * @throws IOException IOException */ public static byte[] download(int connectTimeoutSec, int socketTimeoutSec, String url) throws IOException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; InputStream in = null; ByteArrayOutputStream out = null; try { // httpClient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutSec * 1000) .setConnectionRequestTimeout(connectTimeoutSec * 1000).setSocketTimeout(socketTimeoutSec * 1000) .build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpGet httpGet = new HttpGet(url); httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); in = entity.getContent(); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:org.wuspba.ctams.ws.ITBandContestController.java
protected static void add() throws Exception { ITVenueController.add();/*from w w w . ja v a 2 s . c o m*/ ITJudgeController.add(); ITHiredJudgeController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getBandContests().add(TestFixture.INSTANCE.bandContest); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITVenueController.PATH) .build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.bandContest.setId(doc.getBandContests().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITJudgeController.PATH) .build(); httpPost = new HttpPost(uri); xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); httpPost = new HttpPost(uri); xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.bandContest.setId(doc.getBandContests().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITBandController.java
public static void delete() throws Exception { String id;/*from ww w . j ava2 s . c o m*/ CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); id = doc.getBands().get(0).getId(); EntityUtils.consume(entity); } httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).setParameter("id", id) .build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (HiredJudge j : doc.getHiredJudges()) { ids.add(j.getId());/*from w w w . j a va 2 s. c o m*/ } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } } ITJudgeController.delete(); }
From source file:httpServerClient.app.QuickStart.java
public static void getAllMessages(String[] args) throws Exception { // arguments to run Quick start: // args[0] GET // args[1] IPAddress of server // args[2] port No. CloseableHttpClient httpclient = HttpClients.createDefault(); JacksonObjectMapperToList myList = new JacksonObjectMapperToList(); try {//from www .j a v a 2 s .c om HttpGet httpGet = new HttpGet("http://" + args[1] + ":" + args[2] + "/getAllMessages"); 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(); String result = EntityUtils.toString(entity1); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ //myList.jsonToList(result); myList.jacksonToList(result); myList.PrintList(); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:httpServerClient.app.QuickStart.java
public static void sendMessage(String[] args) throws Exception { // arguments to run Quick start POST: // args[0] POST // args[1] IPAddress of server // args[2] port No. // args[3] user name // args[4] myMessage CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w . j a v a2s. c om HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage"); // httpPost.setEntity(new StringEntity("lubo je kral")); httpPost.setEntity( new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}")); CloseableHttpResponse response1 = httpclient.execute(httpPost); // 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(); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ System.out.println(EntityUtils.toString(entity1)); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:org.cloudsimulator.utility.RestAPI.java
public static ResponseMessageString sendString(final String requestMethod, final String restAPIURI, final String username, final String password, final String stringToSend, final String typeOfString, final String charset) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; ResponseMessageString responseMessageString = null; if ("PUT".equals(requestMethod)) { httpResponse = putRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfString, new ByteArrayEntity(stringToSend.getBytes(charset))); }//from ww w. ja v a2 s . co m if ("POST".equals(requestMethod)) { httpResponse = postRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfString, new ByteArrayEntity(stringToSend.getBytes(charset))); } if (httpResponse != null) { if (httpResponse.getStatusLine() != null) { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } else { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), null); } } else { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(null, null, IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } } httpResponse.close(); } httpClient.close(); return responseMessageString; }
From source file:org.wuspba.ctams.ws.ITVenueController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (Venue v : doc.getVenues()) { ids.add(v.getId());/*from ww w . j a v a 2 s. c om*/ } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } } }
From source file:org.wuspba.ctams.ws.ITBandMemberController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (BandMember m : doc.getBandMembers()) { ids.add(m.getId());/*from ww w . ja v a2 s.co m*/ } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } } ITPersonController.delete(); }
From source file:eionet.gdem.qa.functions.Json.java
/** * Method converts the URL response body into XML format and returns it as String. If the response is not in JSON format, then JsonError object is converted to XML. * @param requestUrl Request URL to JSON format content. * @return String of XML//from w w w .j a v a 2 s .c o m */ public static String jsonRequest2xmlString(String requestUrl) { JsonError error = null; String responseString = null; String xml = null; HttpGet method = null; // Create an instance of HttpClient. CloseableHttpClient client = HttpClients.custom() .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build(); CloseableHttpResponse response = null; try { // Create a method instance. method = new HttpGet(requestUrl); // Provide custom retry handler is necessary //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. response = client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + response.getStatusLine()); error = new JsonError(statusCode, response.getStatusLine().getReasonPhrase()); } else { // Read the response body. HttpEntity entity = response.getEntity(); byte[] responseBody = IOUtils.toByteArray(entity.getContent()); responseString = new String(responseBody, "UTF-8"); } /*} catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal protocol violation.");*/ } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage()); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal transport error."); e.printStackTrace(); } catch (Exception e) { LOGGER.error("Error: " + e.getMessage()); e.printStackTrace(); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error." + e.getMessage()); } finally { // Release the connection. if (method != null) { method.releaseConnection(); } } if (responseString != null) { xml = jsonString2xml(responseString); } else if (error != null) { xml = jsonString2xml(error); } else { xml = jsonString2xml(new JsonError()); } return xml; }