Search in sources :

Example 1 with Callback

use of org.apache.hc.core5.function.Callback in project weicoder by wdcode.

the class HttpAsyncClient method post.

/**
 * 模拟post提交
 *
 * @param url      post提交地址
 * @param data     提交参数
 * @param callback 回调结果
 * @param charset  编码
 */
public static void post(String url, Map<String, Object> data, CallbackVoid<String> callback, String charset) {
    // 声明HttpPost
    HttpPost post = null;
    try {
        // 获得HttpPost
        post = new HttpPost(url);
        post.addHeader(new BasicHeader(HttpConstants.CONTENT_TYPE_KEY, HttpConstants.CONTENT_TYPE_VAL));
        // 如果参数列表为空 data为空map
        if (U.E.isNotEmpty(data)) {
            // 声明参数列表
            List<NameValuePair> list = Lists.newList(data.size());
            // 设置参数
            data.forEach((k, v) -> list.add(new BasicNameValuePair(k, W.C.toString(v))));
            // 设置参数与 编码格式
            post.setEntity(new UrlEncodedFormEntity(list));
        }
        // 执行POST
        CLIENT.execute(SimpleRequestBuilder.copy(post).build(), new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void failed(Exception ex) {
                LOG.error(ex);
            }

            @Override
            public void completed(SimpleHttpResponse result) {
                if (callback != null)
                    callback.callback(result.getBodyText());
            }

            @Override
            public void cancelled() {
            }
        });
    } catch (Exception e) {
        LOG.error(e);
    }
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) NameValuePair(org.apache.hc.core5.http.NameValuePair) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) UrlEncodedFormEntity(org.apache.hc.client5.http.entity.UrlEncodedFormEntity) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse)

Example 2 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class ReactiveEchoProcessor method processRequest.

@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyFuture) throws HttpException, IOException {
    if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
        responseChannel.sendInformation(new BasicHttpResponse(100), context);
    }
    responseChannel.sendResponse(new BasicHttpResponse(200), new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), context);
    responseBodyFuture.execute(requestBody);
}
Also used : BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 3 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class ReactiveRandomProcessor method processRequest.

@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyCallback) throws HttpException, IOException {
    final String method = request.getMethod();
    if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method)) {
        throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
    }
    final URI uri;
    try {
        uri = request.getUri();
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }
    final String path = uri.getPath();
    final int slash = path.lastIndexOf('/');
    if (slash != -1) {
        final String payload = path.substring(slash + 1);
        final long n;
        if (!payload.isEmpty()) {
            try {
                n = Long.parseLong(payload);
            } catch (final NumberFormatException ex) {
                throw new ProtocolException("Invalid request path: " + path);
            }
        } else {
            // random length, but make sure at least something is sent
            n = 1 + (int) (Math.random() * 79.0);
        }
        if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
            responseChannel.sendInformation(new BasicHttpResponse(100), context);
        }
        final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
        final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(n);
        final String hash = ReactiveTestUtils.getStreamHash(n);
        response.addHeader("response-hash-code", hash);
        final BasicEntityDetails basicEntityDetails = new BasicEntityDetails(n, ContentType.APPLICATION_OCTET_STREAM);
        responseChannel.sendResponse(response, basicEntityDetails, context);
        responseBodyCallback.execute(stream);
    } else {
        throw new ProtocolException("Invalid request path: " + path);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 4 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class ServerH2UpgradeHandler method upgrade.

@Override
public void upgrade(final ProtocolIOSession ioSession, final FutureCallback<ProtocolIOSession> callback) {
    final HttpConnectionEventHandler protocolNegotiator = new ServerH2PrefaceHandler(ioSession, http2StreamHandlerFactory, callback);
    ioSession.upgrade(protocolNegotiator);
    try {
        protocolNegotiator.connected(ioSession);
    } catch (final IOException ex) {
        protocolNegotiator.exception(ioSession, ex);
    }
}
Also used : HttpConnectionEventHandler(org.apache.hc.core5.http.impl.nio.HttpConnectionEventHandler) IOException(java.io.IOException)

Example 5 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class ServerHttp1UpgradeHandler method upgrade.

@Override
public void upgrade(final ProtocolIOSession ioSession, final FutureCallback<ProtocolIOSession> callback) {
    final TlsDetails tlsDetails = ioSession.getTlsDetails();
    final ServerHttp1IOEventHandler eventHandler = new ServerHttp1IOEventHandler(http1StreamHandlerFactory.create(tlsDetails != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id, ioSession));
    ioSession.upgrade(eventHandler);
    ioSession.upgrade(eventHandler);
    try {
        eventHandler.connected(ioSession);
        if (callback != null) {
            callback.completed(ioSession);
        }
    } catch (final IOException ex) {
        eventHandler.exception(ioSession, ex);
    }
}
Also used : TlsDetails(org.apache.hc.core5.reactor.ssl.TlsDetails) IOException(java.io.IOException) ServerHttp1IOEventHandler(org.apache.hc.core5.http.impl.nio.ServerHttp1IOEventHandler)

Aggregations

Test (org.junit.jupiter.api.Test)10 IOException (java.io.IOException)6 FutureCallback (org.apache.hc.core5.concurrent.FutureCallback)6 CancellationException (java.util.concurrent.CancellationException)5 TimeoutException (java.util.concurrent.TimeoutException)5 HttpResponse (org.apache.hc.core5.http.HttpResponse)5 ExecutionException (java.util.concurrent.ExecutionException)4 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)4 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)4 TimeoutValueException (org.apache.hc.core5.util.TimeoutValueException)4 Stopwatch (com.google.common.base.Stopwatch)3 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)3 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)3 ContentType (org.apache.hc.core5.http.ContentType)3 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)3 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)2 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)2