List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:org.commonjava.indy.folo.ftest.urls.StoreOneAndSourceStoreUrlInHtmlListingTest.java
@Test public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception { final byte[] data = "this is a test".getBytes(); final ByteArrayInputStream stream = new ByteArrayInputStream(data); final String root = "/path/to/"; final String path = root + "foo.txt"; final String track = "track"; content.store(track, hosted, STORE, path, stream); final IndyClientHttp http = getHttp(); final HttpGet request = http.newRawGet(content.contentUrl(track, hosted, STORE, root)); request.addHeader("Accept", "text/html"); final CloseableHttpClient hc = http.newClient(); final CloseableHttpResponse response = hc.execute(request); final InputStream listing = response.getEntity().getContent(); final String html = IOUtils.toString(listing); // TODO: Charset!! final Document doc = Jsoup.parse(html); for (final Element item : doc.select("a.source-link")) { final String fname = item.text(); System.out.printf("Listing contains: '%s'\n", fname); final String href = item.attr("href"); final String expected = client.content().contentUrl(hosted, STORE); assertThat(fname + " does not have a href", href, notNullValue()); assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName() + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected)); }/*from w ww . j a v a 2s .co m*/ }
From source file:org.commonjava.indy.folo.ftest.urls.StoreOneAndVerifyInHtmlListingTest.java
@Test public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception { final byte[] data = "this is a test".getBytes(); final ByteArrayInputStream stream = new ByteArrayInputStream(data); final String root = "/path/to/"; final String path = root + "foo.txt"; final String track = "track"; content.store(track, hosted, STORE, path, stream); final IndyClientHttp http = getHttp(); final HttpGet request = http.newRawGet(content.contentUrl(track, hosted, STORE, root)); request.addHeader("Accept", "text/html"); final CloseableHttpClient hc = http.newClient(); final CloseableHttpResponse response = hc.execute(request); final InputStream listing = response.getEntity().getContent(); final String html = IOUtils.toString(listing); // TODO: Charset!! final Document doc = Jsoup.parse(html); for (final Element item : doc.select("a.item-link")) { final String fname = item.text(); System.out.printf("Listing contains: '%s'\n", fname); final String href = item.attr("href"); final String expected = client.content().contentUrl(hosted, STORE, root, fname); assertThat(fname + " does not have a href", href, notNullValue()); assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName() + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected)); }//from ww w .j a v a 2 s .c om }
From source file:YexTool.java
private static OpenRtb.BidResponse sendBidRequest(String dspServerAddress, OpenRtb.BidRequest bidRequest, String dataFormat) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(dspServerAddress); switch (dataFormat) { case "pb": post.setEntity(new ByteArrayEntity(bidRequest.toByteArray())); post.setHeader("Content-Type", "application/x-protobuf"); break;/*from w w w . j av a 2s . com*/ case "js": post.setEntity(new StringEntity(openRtbJsonFactory.newWriter().writeBidRequest(bidRequest))); post.setHeader("Content-Type", "application/json"); break; case "jo": post.setEntity(new StringEntity(yexOpenRtbJsonFactory.newWriter().writeBidRequest(bidRequest))); post.setHeader("Content-Type", "application/json"); break; } logger.info("Sending BidRequest to URL: " + dspServerAddress); HttpResponse response = httpclient.execute(post); OpenRtb.BidResponse bidResponse = null; if (response.getStatusLine().getStatusCode() == 200) { try { switch (dataFormat) { case "pb": bidResponse = OpenRtb.BidResponse.parseFrom(response.getEntity().getContent(), extensionRegistry); break; case "js": bidResponse = openRtbJsonFactory.newReader().readBidResponse(response.getEntity().getContent()); OpenRtb.BidResponse.Builder bidResponseBuilder = bidResponse.toBuilder().clearSeatbid(); for (OpenRtb.BidResponse.SeatBid seatBid : bidResponse.getSeatbidList()) { OpenRtb.BidResponse.SeatBid.Builder seatBidBuilder = seatBid.toBuilder().clearBid(); for (OpenRtb.BidResponse.SeatBid.Bid bid : seatBid.getBidList()) { seatBidBuilder.addBid(bid.toBuilder().clearAdm().setAdmNative( openRtbJsonFactory.newNativeReader().readNativeResponse(bid.getAdm()))); } bidResponseBuilder.addSeatbid(seatBidBuilder); } bidResponse = bidResponseBuilder.build(); break; case "jo": bidResponse = yexOpenRtbJsonFactory.newReader() .readBidResponse(response.getEntity().getContent()); break; } } catch (Exception e) { throw new Exception("Error while parse HttpResponse to BidResponse!", e); } bidResponse = electValidBidsInBidResponse(bidRequest, bidResponse); } else { logger.error("Error Response Code: " + response.getStatusLine().getStatusCode()); } return bidResponse; }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsSpringConsumerTest.java
@Test public void testMappingException() throws Exception { HttpGet get = new HttpGet( "http://localhost:" + port1 + "/CxfRsSpringConsumerTest/customerservice/customers/126"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try {/*from w ww. j a v a 2 s .c o m*/ HttpResponse response = httpclient.execute(get); assertEquals("Get a wrong status code", 500, response.getStatusLine().getStatusCode()); assertEquals("Get a worng message header", "exception: Here is the exception", response.getHeaders("exception")[0].toString()); } finally { httpclient.close(); } }
From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java
public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request, Credentials credentials) throws HttpRequestException { LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request); CloseableHttpResponse response;/*from w w w . ja v a2 s . c o m*/ request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0")); request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8")); HttpAuthorization.authorize(request, credentials); // use defaults: 3 retries, 2 second wait between attempts RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy(); while (retryStrategy.shouldRetry()) { try { response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { String responseText = statusLine.getReasonPhrase(); if (responseEntity != null) { responseText = parseError(EntityUtils.toString(responseEntity)); LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText); } throw new HttpResponseException(statusLine.getStatusCode(), responseText); } if (responseEntity == null) { throw new ClientProtocolException("Response contains no content"); } return response; // don't close response yet, it is not consumed! } // if we didn't get a response at all, try again catch (NoHttpResponseException nhre) { LOGGER.warn("Thread: {}, No response from server: Retrying in {} milliseconds, retries left: {}", Thread.currentThread().getId(), retryStrategy.getTimeToWait(), retryStrategy.numberOfTriesLeft); retryStrategy.errorOccurred(); } catch (RetryException re) { throw new HttpRequestException(request, re); } catch (ClientProtocolException uhe) { throw new ConnectionException(request.getURI().toString(), uhe); } catch (IOException ioe) { throw new HttpRequestException(request, ioe); } // here we catch any exception we throw above (plus any we didn't throw ourselves), // log the problem, close any connection held by the request // and then rethrow the exception to the caller. catch (Exception exception) { LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(), exception.getCause().getLocalizedMessage()); request.releaseConnection(); throw exception; } } throw new RuntimeException("Fatal Exception: Should not have occurred!"); }
From source file:sms.SendRequest.java
/** * /*from w ww . j a v a 2 s .c o m*/ * @param moId * @param sender * @param serviceId * @param receiver * @param contentType * @param messageType * @param username * @param messageIndex * @param message * @param operator * @param commandCode * @return * @throws URISyntaxException * @throws IOException */ public String sendRequests(String moId, String sender, String serviceId, String message, String operator, String commandCode, String username) throws URISyntaxException, IOException { Date d = new Date(); SimpleDateFormat fm = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); URI uri = new URIBuilder().setScheme("http").setHost("222.255.167.6:8080").setPath("/SMS/Ctnet/sms") .setParameter("mo_id", moId).setParameter("username", username) .setParameter("key", Common.getMD5(username + "|" + moId + "|ctnet2015")) .setParameter("sender", sender).setParameter("serviceId", serviceId) .setParameter("message", message).setParameter("operator", operator) .setParameter("commandCode", commandCode).build(); HttpGet httpPost = new HttpGet(uri); httpPost.addHeader("content-type", "application/x-www-form-urlencoded"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { return EntityUtils.toString(entity); } else { // Stream content out } } } finally { response.close(); } return ""; }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsConsumerWithBeanTest.java
private void sendPutRequest(String uri) throws Exception { HttpPut put = new HttpPut(uri); StringEntity entity = new StringEntity("string"); entity.setContentType("text/plain"); put.setEntity(entity);/*from ww w. j a va2 s .c o m*/ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try { HttpResponse response = httpclient.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("c20string", EntityUtils.toString(response.getEntity())); } finally { httpclient.close(); } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Post a JSONArray to a remote server and get the response as a JSON object. * @param url URL/*from w w w . j a v a 2s . com*/ * @param array JSONObject Array * @return JSONObject   * @throws IOException   */ public static JSONObject postDataAndGetContentAsJSONObject(String url, LinkedList<JSONObject> array) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(url); postMethod.addHeader(ARCHAPPL_COMPONENT, "true"); postMethod.addHeader("Content-Type", MimeTypeConstants.APPLICATION_JSON); postMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ StringEntity archiverValues = new StringEntity(JSONValue.toJSONString(array), ContentType.APPLICATION_JSON); postMethod.setEntity(archiverValues); if (logger.isDebugEnabled()) { logger.debug("About to make a POST with " + url); } HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); // ArchiverValuesHandler takes over the burden of closing the input stream. try (InputStream is = entity.getContent()) { JSONObject retval = (JSONObject) JSONValue.parse(new InputStreamReader(is)); return retval; } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Post a JSONArray to a remote server and get the response as a JSON object. * @param url URL /*w ww .j a v a2s.c om*/ * @param array JSONObject Array * @return JSONArray   * @throws IOException   */ public static JSONArray postDataAndGetContentAsJSONArray(String url, LinkedList<JSONObject> array) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(url); postMethod.addHeader(ARCHAPPL_COMPONENT, "true"); postMethod.addHeader("Content-Type", MimeTypeConstants.APPLICATION_JSON); postMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ StringEntity archiverValues = new StringEntity(JSONValue.toJSONString(array), ContentType.APPLICATION_JSON); postMethod.setEntity(archiverValues); if (logger.isDebugEnabled()) { logger.debug("About to make a POST with " + url); } HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); // ArchiverValuesHandler takes over the burden of closing the input stream. try (InputStream is = entity.getContent()) { JSONArray retval = (JSONArray) JSONValue.parse(new InputStreamReader(is)); return retval; } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:coyote.dx.web.TestHtmlWorker.java
/** * This is a control test to make sure the HTTP server is running and the * test file is accessible/* ww w . j a v a 2s . c o m*/ */ @Test public void baseServerTest() throws ClientProtocolException, IOException { CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet("http://localhost:" + port + "/data/test.html"); httpGet.addHeader("if-none-match", "*"); CloseableHttpClient httpClient = HttpClients.createDefault(); response = httpClient.execute(httpGet); assertEquals(200, response.getStatusLine().getStatusCode()); } finally { if (response != null) { response.close(); } } }