Search in sources :

Example 6 with FutureCallback

use of org.apache.hc.core5.concurrent.FutureCallback in project weicoder by wdcode.

the class HttpAsyncClient method download.

/**
 * 下载文件
 *
 * @param url      get提交地址
 * @param callback 回调结果
 */
public static void download(String url, final CallbackVoid<byte[]> callback) {
    // 声明HttpGet对象
    HttpGet get = null;
    try {
        // 获得HttpGet对象
        get = new HttpGet(url);
        get.addHeader(new BasicHeader(HttpConstants.CONTENT_TYPE_KEY, HttpConstants.CONTENT_TYPE_VAL));
        // 执行get
        CLIENT.execute(SimpleRequestBuilder.copy(get).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.getBodyBytes());
            }

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

Aggregations

SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)6 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)4 IOException (java.io.IOException)3 ExecutionException (java.util.concurrent.ExecutionException)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 HttpRequest (org.apache.hc.core5.http.HttpRequest)3 Test (org.junit.Test)3 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)2 Timer (com.codahale.metrics.Timer)1 HttpExchange (com.sun.net.httpserver.HttpExchange)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)1 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)1 UrlEncodedFormEntity (org.apache.hc.client5.http.entity.UrlEncodedFormEntity)1 PoolingAsyncClientConnectionManager (org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager)1 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)1 FutureCallback (org.apache.hc.core5.concurrent.FutureCallback)1 NameValuePair (org.apache.hc.core5.http.NameValuePair)1 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)1