Java Code Examples for org.asynchttpclient.BoundRequestBuilder#setBody()

The following examples show how to use org.asynchttpclient.BoundRequestBuilder#setBody() . 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: AsyncHttpCaller.java    From pampas with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Response> asyncCall(AsyncHttpRequest req, ServerInstance serverInstance) {
    final FullHttpRequest httpRequest = req.getFullHttpRequest();
    try {
        final AsyncHttpClient httpClient = this.client;
        BoundRequestBuilder requestBuilder = new BoundRequestBuilder(httpClient,
                httpRequest.method().name(), true);

        requestBuilder.setUri(Uri.create(serverInstance.toUri() + req.getRequestPath()));
        for (Map.Entry<String, String> headerEntry : httpRequest.headers()) {
            if (StringUtils.isNotEmpty(headerEntry.getKey())
                    && !"Host".equals(headerEntry.getKey())) {
                requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }

        }
        requestBuilder.addHeader(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        if (httpRequest.content() != null && httpRequest.content().isReadable()) {
            //请求body转换为ByteBuffer,并且设置为只读,ByteBuf复用 堆内存中的数据 zero copy
            ByteBuffer readOnlyBuffer = httpRequest.content().nioBuffer().asReadOnlyBuffer();
            requestBuilder.setBody(readOnlyBuffer);
        }
        ListenableFuture<Response> listenableFuture = requestBuilder.execute();
        return listenableFuture.toCompletableFuture();

    } catch (Exception ex) {
        log.warn("执行调用报错:{}", ex);
        CompletableFuture<Response> exceptionFuture = CompletableFuture.completedFuture(null);
        exceptionFuture.completeExceptionally(ex);
        return exceptionFuture;
    }
}
 
Example 2
Source File: ClickhouseWriterTest.java    From flink-clickhouse-sink with MIT License 5 votes vote down vote up
private void send(String data, String url, String basicCredentials, AtomicInteger counter) {
    String query = String.format("INSERT INTO %s VALUES %s ", "groot3.events", data);
    BoundRequestBuilder requestBuilder = asyncHttpClient.preparePost(url).setHeader("Authorization", basicCredentials);
    requestBuilder.setBody(query);
    ListenableFuture<Response> whenResponse = asyncHttpClient.executeRequest(requestBuilder.build());
    Runnable callback = () -> {
        try {
            Response response = whenResponse.get();
            System.out.println(Thread.currentThread().getName() + " " + response);

            if (response.getStatusCode() != 200) {
                System.out.println(Thread.currentThread().getName() + " try to retry...");
                int attempt = counter.incrementAndGet();
                if (attempt > MAX_ATTEMPT) {
                    System.out.println("Failed ");
                } else {
                    send(data, url, basicCredentials, counter);
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    };

    Executor executor = ForkJoinPool.commonPool();
    whenResponse.addListener(callback, executor);
}
 
Example 3
Source File: AsyncHttpConnector.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Response> oneShot(InetSocketAddress host, ClientRequest request) {
    ClientRequest currentRequest = new ClientRequest(request);
    URI newUri = replaceWithNew(host, currentRequest.getUri());
    currentRequest.setUri(newUri);

    BoundRequestBuilder builder =
            httpClient.prepare(currentRequest.getMethod(), currentRequest.getUri().toString());

    if (currentRequest.hasEntity()) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        currentRequest.setStreamProvider(contentLength -> outStream);
        try {
            currentRequest.writeEntity();
        } catch (IOException e) {
            CompletableFuture<Response> r = new CompletableFuture<>();
            r.completeExceptionally(e);
            return r;
        }

        builder.setBody(outStream.toByteArray());
    }

    currentRequest.getHeaders().forEach((key, headers) -> {
        if (!HttpHeaders.USER_AGENT.equals(key)) {
            builder.addHeader(key, headers);
        }
    });

    return builder.execute().toCompletableFuture();
}