Apache HttpClient 5 筆記: SSL, Proxy 和 Multipart Upload

2023-01-01 06:00:11

Apache HttpClient 5

最近要在非SpringBoot環境呼叫OpenFeign介面, 需要用到httpclient, 注意到現在 HttpClient 版本已經到 5.2.1 了. 之前在版本4中的一些方法已經變成 deprecated, 於是將之前的工具類升級一下, 順便把中間遇到的問題記錄一下

基礎使用方法

首先參考Apache官方的快速開始 httpcomponents-client-5.2.x quickstart, 這是頁面上給的例子

Post請求

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));

    try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
        System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    }
}

Get請求

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
    HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
        System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    }
}

替換 Deprecated 的 execute 方法

上面的例子可以正常執行, 但是在HttpClient5中, CloseableHttpResponse execute(ClassicHttpRequest request) 這個方法已經被標記為 Deprecated

@Deprecated
HttpResponse execute(ClassicHttpRequest var1) throws IOException;

@Deprecated
HttpResponse execute(ClassicHttpRequest var1, HttpContext var2) throws IOException;

@Deprecated
ClassicHttpResponse execute(HttpHost var1, ClassicHttpRequest var2) throws IOException;

@Deprecated
HttpResponse execute(HttpHost var1, ClassicHttpRequest var2, HttpContext var3) throws IOException;

取而代之的, 是這四個帶 HttpClientResponseHandler 引數的 execute 方法

<T> T execute(ClassicHttpRequest var1, HttpClientResponseHandler<? extends T> var2) throws IOException;
<T> T execute(ClassicHttpRequest var1, HttpContext var2, HttpClientResponseHandler<? extends T> var3) throws IOException;
<T> T execute(HttpHost var1, ClassicHttpRequest var2, HttpClientResponseHandler<? extends T> var3) throws IOException;
<T> T execute(HttpHost var1, ClassicHttpRequest var2, HttpContext var3, HttpClientResponseHandler<? extends T> var4) throws IOException;
}

這個 HttpClientResponseHandler 作為響應的處理方法, 裡面只有一個介面方法(要注意到這是一個函數式介面)

@FunctionalInterface
public interface HttpClientResponseHandler<T> {
    T handleResponse(ClassicHttpResponse var1) throws HttpException, IOException;
}

JDK中提供了一個預設的實現, BasicHttpClientResponseHandler(基於 AbstractHttpClientResponseHandler)

public abstract class AbstractHttpClientResponseHandler<T> implements HttpClientResponseHandler<T> {
    public AbstractHttpClientResponseHandler() {
    }

    public T handleResponse(ClassicHttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();
        if (response.getCode() >= 300) {
            EntityUtils.consume(entity);
            throw new HttpResponseException(response.getCode(), response.getReasonPhrase());
        } else {
            return entity == null ? null : this.handleEntity(entity);
        }
    }

    public abstract T handleEntity(HttpEntity var1) throws IOException;
}

public class BasicHttpClientResponseHandler extends AbstractHttpClientResponseHandler<String> {
    public BasicHttpClientResponseHandler() {
    }

    public String handleEntity(HttpEntity entity) throws IOException {
        try {
            return EntityUtils.toString(entity);
        } catch (ParseException var3) {
            throw new ClientProtocolException(var3);
        }
    }

    public String handleResponse(ClassicHttpResponse response) throws IOException {
        return (String)super.handleResponse(response);
    }
}

這樣基礎的使用方式就改為了下面的形式

public static void main(final String[] args) throws Exception {
    final CloseableHttpClient httpClient = HttpClients.createDefault();
    try (httpClient) {
        final HttpGet httpGet = new HttpGet("https://www.baidu.com/home/other/data/weatherInfo");
        final String responseBody = httpClient.execute(httpGet, new BasicHttpClientResponseHandler());
        System.out.println(responseBody);
    }
}

使用自定義的函數式方法處理響應

可以看到, 上面的 BasicHttpClientResponseHandler 是一個比較簡單的實現, 大於300的響應狀態碼直接丟擲異常, 其它的讀出字串. 這樣的處理方式對於更精細的使用場景是不夠的

  • 需要根據響應狀態碼判斷時
  • 需要對響應解析為Java類時
  • 需要壓住異常, 統一返回類物件時

之前在 HttpClient4 時, 可以通過CloseableHttpResponse response = client.execute(httpRequest), 對 response 進行判斷, 現在response已經完全被handler 包裹, 需要通過自定義函數式方法處理響應, 看下面的例子

首先定義一個響應結果類, 資料部分使用泛型

@Data
public class Client5Resp<T> implements Serializable {
    private int code;
    private String raw;
    private T data;
    
    public Client5Resp(int code, String raw, T data) {
        this.code = code;
        this.raw = raw;
        this.data = data;
    }
}

然後對響應結果自定義 handler, 因為是函數式介面, 所以很方便在方法中直接定義, 處理的邏輯是:

  1. 如果 T 泛型為String, 直接將 body 作為資料返回
  2. 其它的 T 泛型, 用 Jackson 解開之後返回
  3. 將 status code 一併返回
private static <T> Client5Resp<T> httpRequest(
        TypeReference<T> tp,
        HttpUriRequest httpRequest) {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        Client5Resp<T> resp = client.execute(httpRequest, response -> {
            if (response.getEntity() != null) {
                String body = EntityUtils.toString(response.getEntity());
                if (tp.getType() == String.class) {
                    return new Client5Resp<>(response.getCode(), body, (T)body);
                } 
                // 當需要區分更多型別時可以增加定義
                else {
                    T t = JacksonUtil.extractByType(body, tp);
                    return new Client5Resp<>(response.getCode(), body, t);
                }
            } else {
                return new Client5Resp<>(response.getCode(), null, null);
            }
        });
        log.info("rsp:{}, body:{}", resp.getCode(), resp.getRaw());
        return resp;
    } catch (IOException|NoSuchAlgorithmException|KeyStoreException|KeyManagementException e) {
        // 當異常也需要返回 Client5Resp 型別物件時可以在catch中封裝
        log.error(e.getMessage(), e);
    }
    return null;
}

自定義請求設定和Header

首先是超時設定

RequestConfig defaultRequestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(60, TimeUnit.SECONDS)
        .setResponseTimeout(60, TimeUnit.SECONDS)
        .build();

然後是 Header

List<Header> headers = List.of(
    new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
    new BasicHeader(HttpHeaders.ACCEPT, "application/json"));

在 HttpGet/HttpPost 中設定

HttpGet httpGet = new HttpGet(...);
if (headers != null) {
    for (Header header : headers) {
        httpGet.addHeader(header);
    }
}
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
httpGet.setConfig(requestConfig);

自定義 HttpClient 增加 SSL TrustAllStrategy

在 HttpClient5 中, 增加 SSL TrustAllStrategy 的方法也有變化, 這是獲取 CloseableHttpClient 的程式碼

final RequestConfig defaultRequestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(60, TimeUnit.SECONDS)
        .setResponseTimeout(60, TimeUnit.SECONDS)
        .build();
final BasicCookieStore defaultCookieStore = new BasicCookieStore();
final SSLContext sslcontext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustAllStrategy()).build();
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
        .setSslContext(sslcontext).build();
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
        .setSSLSocketFactory(sslSocketFactory).build();
return HttpClients.custom()
        .setDefaultCookieStore(defaultCookieStore)
        .setDefaultRequestConfig(defaultRequestConfig)
        .setConnectionManager(cm)
        .evictExpiredConnections()
        .build();

增加 Http Proxy

固定的 Proxy

在 HttpClient5 中, RequestConfig.Builder.setProxy()方法已經 Deprecated

@Deprecated
public RequestConfig.Builder setProxy(HttpHost proxy) {
    this.proxy = proxy;
    return this;
}

需要使用 HttpClientBuilder.setRoutePlanner(HttpRoutePlanner routePlanner) 進行設定, 和SSL一起, 獲取client的程式碼變成

final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
return HttpClients.custom()
        .setDefaultCookieStore(defaultCookieStore)
        .setDefaultRequestConfig(defaultRequestConfig)
        .setRoutePlanner(routePlanner)
        .setConnectionManager(cm)
        .evictExpiredConnections()
        .build();

如果需要使用者名稱密碼, 需要再增加一個 CredentialsProvider, 變成

final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(proxyHost, proxyPort),
        new UsernamePasswordCredentials(authUser, authPasswd.toCharArray()));

return HttpClients.custom()
        .setDefaultCookieStore(defaultCookieStore)
        .setDefaultRequestConfig(defaultRequestConfig)
        .setDefaultCredentialsProvider(credsProvider)
        .setRoutePlanner(routePlanner)
        .setConnectionManager(cm)
        .evictExpiredConnections()
        .build();

動態 Proxy

如果需要隨時切換 proxy, 需要自己實現一個 HttpRoutePlanner

public static class DynamicProxyRoutePlanner implements HttpRoutePlanner {
    private DefaultProxyRoutePlanner planner;

    public DynamicProxyRoutePlanner(HttpHost host){
        planner = new DefaultProxyRoutePlanner(host);
    }

    public void setProxy(HttpHost host){
        planner = new DefaultProxyRoutePlanner(host);
    }

    public HttpRoute determineRoute(HttpHost target, HttpContext context) throws HttpException {
        return planner.determineRoute(target, context);
    }
}

然後在程式碼中進行切換

HttpHost proxy = new HttpHost("127.0.0.1", 1080);
DynamicProxyRoutePlanner routePlanner = new DynamicProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
    .setRoutePlanner(routePlanner)
    .build();
// 換代理
routePlanner.setProxy(new HttpHost("192.168.0.1", 1081));

構造 Multipart 檔案上傳請求

首先是構造 HttpEntity 的方法, 這個方法中設定請求為 1個檔案 + 多個隨表單引數

public static HttpEntity httpEntityBuild(NameValuePair fileNvp, List<NameValuePair> nvps) {
    File file = new File(fileNvp.getValue());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);
    if (nvps != null && nvps.size() > 0) {
        for (NameValuePair nvp : nvps) {
            builder.addTextBody(nvp.getName(), nvp.getValue(), ContentType.DEFAULT_BINARY);
        }
    }
    builder.addBinaryBody(fileNvp.getName(), file, ContentType.DEFAULT_BINARY, fileNvp.getValue());
    return builder.build();
}

請求流程

// 構造一個檔案引數, 其它引數留空
NameValuePair fileNvp = new BasicNameValuePair("sendfile", filePath);
HttpEntity entity = httpEntityBuild(fileNvp, null);
HttpPost httpPost = new HttpPost(api);
httpPost.setEntity(entity);

try (CloseableHttpClient client = getClient(...)) {
    Client5Resp<T> resp = client.execute(httpPost, response->{
        ...
    });

注意: 在使用 HttpMultipartMode 時對 HttpEntity 設定 Header 要謹慎, 因為 HttpClient 會對 Content-Type增加 Boundary 字尾, 而這個是伺服器端判斷檔案邊界的重要引數. 如果設定自定義 Header, 需要檢查 boundary 是否正確生成. 如果沒有的話需要自定義 Content-Type 將 boundary 加進去, 並且通過 EntityBuilder.setBoundary() 將自定義的 boundary 值傳給 HttpEntity.

Links