List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:org.wuspba.ctams.ws.ITSoloContestController.java
protected static void add() throws Exception { ITVenueController.add();// w ww.ja v a2 s .co m ITHiredJudgeController.add(); ITJudgeController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getPeople().add(TestFixture.INSTANCE.andy); doc.getPeople().add(TestFixture.INSTANCE.jamie); doc.getPeople().add(TestFixture.INSTANCE.bob); doc.getPeople().add(TestFixture.INSTANCE.eoin); 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.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin); doc.getSoloContests().add(TestFixture.INSTANCE.soloContest); 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.soloContest.setId(doc.getSoloContests().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.soloContest.setId(doc.getSoloContests().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.ITJudgeController.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 (Judge j : doc.getJudges()) { ids.add(j.getId());/*from w ww . j a v a 2 s. com*/ } 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(); ITJudgeQualificationController.delete(); }
From source file:com.zxy.commons.httpclient.HttpclientUtils.java
/** * Post url/*from w w w . j a va2 s . co m*/ * * @param connectTimeoutSec () * @param socketTimeoutSec ??() * @param url url? * @param params {@link org.apache.http.NameValuePair} params * <p> * example:{@code params.add(new BasicNameValuePair("id", "123456"));} * @return post?? * @throws ClientProtocolException ClientProtocolException * @throws IOException IOException * @see org.apache.http.NameValuePair * @see org.apache.http.message.BasicNameValuePair */ public static String post(int connectTimeoutSec, int socketTimeoutSec, String url, List<NameValuePair> params) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = 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(); HttpPost httppost = new HttpPost(url); UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, Charsets.UTF_8); httppost.setEntity(uefEntity); httpResponse = httpClient.execute(httppost); HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity, Charsets.UTF_8); } finally { HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:org.wuspba.ctams.ws.ITJudgeQualificationController.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 (JudgeQualification q : doc.getJudgeQualifications()) { ids.add(q.getId());// w w w . j a v a 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); } } } } }
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsAndInterOpsDUnitTest.java
public static void fetchRestServerEndpoints(String restEndpoint) { HttpGet get = new HttpGet(restEndpoint + "/servers"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response; try {//from w ww . j av a 2 s . c o m response = httpclient.execute(get); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } //validate the satus code assertEquals(response.getStatusLine().getStatusCode(), 200); if (response.getStatusLine().getStatusCode() == 200) { JSONArray jsonArray = new JSONArray(str.toString()); //verify total number of REST service endpoints in DS assertEquals(jsonArray.length(), 2); } } catch (ClientProtocolException e) { e.printStackTrace(); fail(" Rest Request should not have thrown ClientProtocolException!"); } catch (IOException e) { e.printStackTrace(); fail(" Rest Request should not have thrown IOException!"); } catch (JSONException e) { e.printStackTrace(); fail(" Rest Request should not have thrown JSONException!"); } }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Print out the HTTP Response body - for debugging purposes *///from w ww . java 2s . c o m @SuppressWarnings("unused") private static void printResponseBody(CloseableHttpResponse response) { if (LOGGER.isLoggable(Level.FINER)) { HttpEntity entity = response.getEntity(); if (entity == null) return; StringBuffer logMessage = new StringBuffer("Response Body:"); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line = reader.readLine(); while (line != null) { logMessage.append(NEW_LINE).append(line); line = reader.readLine(); } LOGGER.finer(logMessage.toString()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } } } }
From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java
static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext) throws OIDCClientException, SSLConnectionException { Validate.notNull(httpRequest, "httpRequest"); Validate.notNull(sslContext, "sslContext"); RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build(); CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config) .build();/*from w w w.jav a 2 s . c o m*/ CloseableHttpResponse closeableHttpResponse = null; try { HttpRequestBase httpTask = httpRequest.toHttpTask(); closeableHttpResponse = client.execute(httpTask); int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode(); StatusCode statusCode; try { statusCode = StatusCode.parse(statusCodeInt); } catch (ParseException e) { throw new OIDCClientException("failed to parse status code", e); } JSONObject jsonContent = null; HttpEntity httpEntity = closeableHttpResponse.getEntity(); if (httpEntity != null) { ContentType contentType; try { contentType = ContentType.get(httpEntity); } catch (UnsupportedCharsetException | org.apache.http.ParseException e) { throw new OIDCClientException("Error in setting content type in HTTP response."); } if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) { throw new OIDCClientException("unsupported charset: " + contentType.getCharset()); } if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) { throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType()); } String content = EntityUtils.toString(httpEntity); try { jsonContent = JSONUtils.parseJSONObject(content); } catch (ParseException e) { throw new OIDCClientException("failed to parse json response", e); } } closeableHttpResponse.close(); client.close(); return HttpResponse.createJsonResponse(statusCode, jsonContent); } catch (IOException e) { throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e); } }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get./* w w w . j a v a 2 s. c o m*/ * * @param uri * the uri * @param headers * the headers * @return the string * @throws Exception * the exception */ public static String doGet(URI uri, HashMap<String, String> headers) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String respString = null; try { /* * HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs. * * URI uri = new URIBuilder() .setScheme("http") .setHost("hc.apache.org/") // .setPath("/search") // .setParameter("q", * "httpclient") // .setParameter("btnG", "Google Search") // .setParameter("aq", "f") // .setParameter("oq", "") .build(); */ HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } 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 entity = response1.getEntity(); // do something useful with the response body if (entity != null) { respString = EntityUtils.toString(entity); } // and ensure it is fully consumed EntityUtils.consume(entity); } finally { response1.close(); } } finally { httpclient.close(); } return respString; }
From source file:org.wuspba.ctams.ws.ITBandContestController.java
protected static void delete() throws Exception { String id;//from w w w. j a v a 2 s . co 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.getBandContests().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); } } } ITVenueController.delete(); ITHiredJudgeController.delete(); ITJudgeController.delete(); }
From source file:com.joyent.manta.http.EncryptedHttpHelperTest.java
/** * Builds a fully mocked {@link EncryptionHttpHelper} that is setup to * be configured for one cipher/mode and executes requests in another * cipher/mode.//from w w w . java2 s.c o m */ private static EncryptionHttpHelper fakeEncryptionHttpHelper(String path) throws Exception { MantaConnectionContext connectionContext = mock(MantaConnectionContext.class); StandardConfigContext config = new StandardConfigContext(); SupportedCipherDetails cipherDetails = AesCbcCipherDetails.INSTANCE_192_BIT; config.setClientEncryptionEnabled(true) .setEncryptionPrivateKeyBytes(SecretKeyUtils.generate(cipherDetails).getEncoded()) .setEncryptionAlgorithm(cipherDetails.getCipherId()); EncryptionHttpHelper httpHelper = new EncryptionHttpHelper(connectionContext, new MantaHttpRequestFactory(UnitTestConstants.UNIT_TEST_URL), config); URI uri = URI.create(DEFAULT_MANTA_URL + "/" + path); CloseableHttpResponse fakeResponse = mock(CloseableHttpResponse.class); StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); SupportedCipherDetails objectCipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT; Header[] headers = new Header[] { // Notice this is a different cipher than the one set in config new BasicHeader(MantaHttpHeaders.ENCRYPTION_CIPHER, objectCipherDetails.getCipherId()) }; when(fakeResponse.getAllHeaders()).thenReturn(headers); when(fakeResponse.getStatusLine()).thenReturn(statusLine); BasicHttpEntity fakeEntity = new BasicHttpEntity(); InputStream source = IOUtils.toInputStream("I'm a stream", StandardCharsets.US_ASCII); EofSensorInputStream stream = new EofSensorInputStream(source, null); fakeEntity.setContent(stream); when(fakeResponse.getEntity()).thenReturn(fakeEntity); when(connectionContext.getHttpClient()).thenReturn(new FakeCloseableHttpClient(fakeResponse)); return httpHelper; }