Java Code Examples for org.apache.http.impl.nio.client.CloseableHttpAsyncClient#execute()
The following examples show how to use
org.apache.http.impl.nio.client.CloseableHttpAsyncClient#execute() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApacheHttpAsyncClientPluginIT.java From glowroot with Apache License 2.0 | 6 votes |
@Override public void transactionMarker() throws Exception { CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); httpClient.start(); HttpHost httpHost = new HttpHost("localhost", getPort()); HttpPost httpPost = new HttpPost("/hello4"); SimpleFutureCallback callback = new SimpleFutureCallback(); Future<HttpResponse> future = httpClient.execute(httpHost, httpPost, callback); callback.latch.await(); httpClient.close(); int responseStatusCode = future.get().getStatusLine().getStatusCode(); if (responseStatusCode != 200) { throw new IllegalStateException( "Unexpected response status code: " + responseStatusCode); } }
Example 2
Source File: MicrometerHttpClientInterceptorTest.java From micrometer with Apache License 2.0 | 6 votes |
@Test void uriIsReadFromHttpHeader(@WiremockResolver.Wiremock WireMockServer server) throws Exception { server.stubFor(any(anyUrl())); MicrometerHttpClientInterceptor interceptor = new MicrometerHttpClientInterceptor(registry, Tags.empty(), true); CloseableHttpAsyncClient client = asyncClient(interceptor); client.start(); HttpGet request = new HttpGet(server.baseUrl()); request.addHeader(DefaultUriMapper.URI_PATTERN_HEADER, "/some/pattern"); Future<HttpResponse> future = client.execute(request, null); HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(registry.get("httpcomponents.httpclient.request").tag("uri", "/some/pattern").tag("status", "200").timer().count()) .isEqualTo(1); client.close(); }
Example 3
Source File: HttpClient.java From aliyun-tsdb-java-sdk with Apache License 2.0 | 6 votes |
public static HttpResponse redirectResponse(HttpResponse httpResponse, HttpEntityEnclosingRequestBase request, CloseableHttpAsyncClient httpclient) throws ExecutionException, InterruptedException { HttpResponse result = null; Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); for (Header header : headers) { if (header.getName().equalsIgnoreCase(HttpHeaders.LOCATION)) { String newUrl = header.getValue(); request.setURI(URI.create(newUrl)); Future<HttpResponse> future = httpclient.execute(request, null); result = future.get(); break; } } if (result == null) { return httpResponse; } return result; }
Example 4
Source File: HttpAsyncClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234"); cookie.setDomain(COOKIE_DOMAIN); cookie.setPath("/"); cookieStore.addCookie(cookie); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build(); client.start(); final HttpGet request = new HttpGet(HOST_WITH_COOKIE); final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); final Future<HttpResponse> future = client.execute(request, localContext, null); final HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
Example 5
Source File: AsyncClientAuthentication.java From yunpian-java-sdk with MIT License | 6 votes |
public static void main(String[] args) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password")); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); try { HttpGet httpget = new HttpGet("http://localhost/"); System.out.println("Executing request " + httpget.getRequestLine()); Future<HttpResponse> future = httpclient.execute(httpget, null); HttpResponse response = future.get(); System.out.println("Response: " + response.getStatusLine()); System.out.println("Shutting down"); } finally { httpclient.close(); } }
Example 6
Source File: ApacheHttpAsyncClientPluginIT.java From glowroot with Apache License 2.0 | 6 votes |
@Override public void transactionMarker() throws Exception { CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); httpClient.start(); HttpHost httpHost = new HttpHost("localhost", getPort()); HttpGet httpGet = new HttpGet("/hello2"); SimpleFutureCallback callback = new SimpleFutureCallback(); Future<HttpResponse> future = httpClient.execute(httpHost, httpGet, callback); callback.latch.await(); httpClient.close(); int responseStatusCode = future.get().getStatusLine().getStatusCode(); if (responseStatusCode != 200) { throw new IllegalStateException( "Unexpected response status code: " + responseStatusCode); } }
Example 7
Source File: HttpAsyncClientLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); client.start(); final HttpGet request = new HttpGet(HOST); final Future<HttpResponse> future = client.execute(request, null); final HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
Example 8
Source File: HttpDownloadHandler.java From cetty with Apache License 2.0 | 5 votes |
private void asyncHttpClientDownload(HandlerContext ctx, Seed seed) { Payload payload = ctx.cetty().getPayload(); CloseableHttpAsyncClient httpAsyncClient = ctx.cetty().getHttpAsyncClient(); try { httpAsyncClient.execute(convertHttpUriRequest(seed, payload), convertHttpClientContext(seed, payload), new CallBack(seed, ctx, payload)); } catch (Exception e) { logger.warn("download {} page error !", seed.getUrl(), e); } }
Example 9
Source File: ClosableAsyncHttpClientIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().useSystemProperties().build(); httpClient.start(); try { HttpPost httpRequest = new HttpPost(webServer.getCallHttpUrl()); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("param1", "value1")); httpRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8.name())); Future<HttpResponse> responseFuture = httpClient.execute(httpRequest, null); HttpResponse response = (HttpResponse) responseFuture.get(); if ((response != null) && (response.getEntity() != null)) { EntityUtils.consume(response.getEntity()); } } finally { httpClient.close(); } PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", CloseableHttpAsyncClient.class.getMethod("execute", HttpUriRequest.class, FutureCallback.class))); final String destinationId = webServer.getHostAndPort(); final String httpUrl = webServer.getCallHttpUrl(); verifier.verifyTrace(async( event("HTTP_CLIENT_4", Class.forName("org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl").getMethod("start"), null, null, destinationId, annotation("http.url", httpUrl), annotation("http.entity", "param1=value1")), event("ASYNC","Asynchronous Invocation"), event("HTTP_CLIENT_4_INTERNAL", BasicFuture.class.getMethod("completed", Object.class)) )); verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", BasicFuture.class.getMethod("get"))); verifier.verifyTraceCount(0); }
Example 10
Source File: ApacheHttpAsyncClientPluginIT.java From glowroot with Apache License 2.0 | 5 votes |
@Override public void transactionMarker() throws Exception { CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); httpClient.start(); HttpGet httpGet = new HttpGet("http://localhost:" + getPort() + "/hello1"); SimpleFutureCallback callback = new SimpleFutureCallback(); Future<HttpResponse> future = httpClient.execute(httpGet, callback); callback.latch.await(); httpClient.close(); int responseStatusCode = future.get().getStatusLine().getStatusCode(); if (responseStatusCode != 200) { throw new IllegalStateException( "Unexpected response status code: " + responseStatusCode); } }
Example 11
Source File: HttpAsyncClientLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUseProxyWithHttpClient_thenCorrect() throws Exception { final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); client.start(); final HttpHost proxy = new HttpHost("127.0.0.1", 8080); final RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); final HttpGet request = new HttpGet(HOST_WITH_PROXY); request.setConfig(config); final Future<HttpResponse> future = client.execute(request, null); final HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
Example 12
Source File: AsyncClientHttpExchangeFutureCallback.java From yunpian-java-sdk with MIT License | 5 votes |
public static void main(final String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build(); try { httpclient.start(); final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
Example 13
Source File: ApacheHttpAsyncClientPluginIT.java From glowroot with Apache License 2.0 | 5 votes |
@Override public void transactionMarker() throws Exception { CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); httpClient.start(); HttpPost httpPost = new HttpPost("http://localhost:" + getPort() + "/hello3"); SimpleFutureCallback callback = new SimpleFutureCallback(); Future<HttpResponse> future = httpClient.execute(httpPost, callback); callback.latch.await(); httpClient.close(); int responseStatusCode = future.get().getStatusLine().getStatusCode(); if (responseStatusCode != 200) { throw new IllegalStateException( "Unexpected response status code: " + responseStatusCode); } }
Example 14
Source File: ZeroCopyHttpExchange.java From yunpian-java-sdk with MIT License | 5 votes |
public static void main(final String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try { httpclient.start(); File upload = new File(args[0]); File download = new File(args[1]); ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload, ContentType.create("text/plain")); ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new ClientProtocolException("Upload failed: " + response.getStatusLine()); } return file; } }; Future<File> future = httpclient.execute(httpost, consumer, null); File result = future.get(); System.out.println("Response file length: " + result.length()); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
Example 15
Source File: MicrometerHttpClientInterceptorTest.java From micrometer with Apache License 2.0 | 5 votes |
@Test void asyncRequest(@WiremockResolver.Wiremock WireMockServer server) throws Exception { server.stubFor(any(anyUrl())); CloseableHttpAsyncClient client = asyncClient(); client.start(); HttpGet request = new HttpGet(server.baseUrl()); Future<HttpResponse> future = client.execute(request, null); HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(registry.get("httpcomponents.httpclient.request").timer().count()).isEqualTo(1); client.close(); }
Example 16
Source File: ITTracingHttpAsyncClientBuilder.java From brave with Apache License 2.0 | 4 votes |
static void invoke(CloseableHttpAsyncClient client, HttpUriRequest req) throws IOException { Future<HttpResponse> future = client.execute(req, null); HttpResponse response = blockOnFuture(future); EntityUtils.consume(response.getEntity()); }
Example 17
Source File: AbstractStockServiceImpl.java From Thunder with Apache License 2.0 | 4 votes |
@Override public List<Stock> execute(String[] codes, StockType stockType, boolean simple) { barrier.reset(); InterfaceType interfaceType = getInterfaceType(); if (interfaceType == InterfaceType.SINA) { if (stockType == StockType.ZHULI || stockType == StockType.PANKOU) { return null; } } String url = getUrl(codes, stockType); if (url == null) { return null; } String id = RandomUtil.uuidRandom(); AbstractStockCallback callback = getCallback(); callback.setCodes(codes); callback.setStockType(stockType); callback.setInterfaceType(interfaceType); callback.setSimple(simple); callback.setId(id); callback.setCacheMap(cacheMap); callback.setBarrier(barrier); HttpGet httpGet = new HttpGet(url); CloseableHttpAsyncClient httpAsyncClient = clientExecutor.getClient(); httpAsyncClient.execute(httpGet, callback); try { barrier.await(); } catch (Exception e) { e.printStackTrace(); return null; } finally { httpGet.reset(); } List<Stock> stock = cacheMap.get(id); cacheMap.remove(id); return stock; }
Example 18
Source File: HttpClient.java From aliyun-tsdb-java-sdk with Apache License 2.0 | 4 votes |
public static HttpResponse authResponse(HttpEntityEnclosingRequestBase request, CloseableHttpAsyncClient httpclient) throws ExecutionException, InterruptedException { Future<HttpResponse> future = httpclient.execute(request, null); return future.get(); }
Example 19
Source File: HttpClientService.java From waterdrop with Apache License 2.0 | 3 votes |
public static void execAsyncGet(String baseUrl, List<BasicNameValuePair> urlParams, FutureCallback callback) throws Exception { if (baseUrl == null) { logger.warn("we don't have base url, check config"); throw new ConfigException("missing base url"); } HttpRequestBase httpMethod = new HttpGet(baseUrl); CloseableHttpAsyncClient hc = null; try { hc = HttpClientFactory.getInstance().getHttpAsyncClientPool() .getAsyncHttpClient(); hc.start(); HttpClientContext localContext = HttpClientContext.create(); BasicCookieStore cookieStore = new BasicCookieStore(); if (null != urlParams) { String getUrl = EntityUtils.toString(new UrlEncodedFormEntity(urlParams)); httpMethod.setURI(new URI(httpMethod.getURI().toString() + "?" + getUrl)); } localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); hc.execute(httpMethod, localContext, callback); } catch (Exception e) { e.printStackTrace(); } }
Example 20
Source File: HttpClientUtil.java From rapidoid with Apache License 2.0 | 3 votes |
static Future<HttpResp> request(HttpReq config, CloseableHttpAsyncClient client, Callback<HttpResp> callback, boolean close) { HttpRequestBase req = createRequest(config); if (Log.isDebugEnabled()) Log.debug("Starting HTTP request", "request", req.getRequestLine()); Promise<HttpResp> promise = Promises.create(); FutureCallback<HttpResponse> cb = callback(client, callback, promise, close); client.execute(req, cb); return promise; }