From 3e53113401724a8ed9b862d23e083183c70d6007 Mon Sep 17 00:00:00 2001 From: masutangu Date: Fri, 22 Nov 2024 10:55:21 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20apacheHttpClientAdap?= =?UTF-8?q?ter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/build.gradle | 2 + .../core/http/DefaultHttpClientBuilder.java | 89 +- .../http/apache/ApacheHttpClientAdapter.java | 169 ++ .../http/ApacheHttpClientAdapterTest.java | 1541 +++++++++++++++++ .../http/ApacheHttpClientAdapterV2Test.java | 79 + .../pay/java/core/http/HttpClientTest.java | 2 +- gradle.properties | 1 + 7 files changed, 1871 insertions(+), 12 deletions(-) create mode 100644 core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java create mode 100644 core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java create mode 100644 core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java diff --git a/core/build.gradle b/core/build.gradle index f1c55c85..cb084271 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -18,6 +18,8 @@ jar { dependencies { implementation "com.google.code.gson:gson:${gsonVersion}" implementation "com.squareup.okhttp3:okhttp:${okhttpVersion}" + implementation "org.apache.httpcomponents:httpmime:${apachehttpVersion}" + implementation "org.apache.httpcomponents:httpclient:${apachehttpVersion}" implementation "org.slf4j:slf4j-api:${slf4jVersion}" testImplementation "junit:junit:${junitVersion}" diff --git a/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java index af81a2c2..d4e648a5 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java @@ -1,14 +1,22 @@ package com.wechat.pay.java.core.http; +import java.net.Proxy; import static java.util.Objects.requireNonNull; +import java.util.concurrent.TimeUnit; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.auth.Credential; import com.wechat.pay.java.core.auth.Validator; +import com.wechat.pay.java.core.http.apache.ApacheHttpClientAdapter; import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; import com.wechat.pay.java.core.http.okhttp.OkHttpMultiDomainInterceptor; -import java.net.Proxy; -import java.util.concurrent.TimeUnit; + import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; @@ -30,6 +38,8 @@ public class DefaultHttpClientBuilder new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS)) .build(); private okhttp3.OkHttpClient customizeOkHttpClient; + private CloseableHttpClient customizeApacheHttpClient; + private boolean useApacheHttpClient = false; // private int readTimeoutMs = -1; private int writeTimeoutMs = -1; private int connectTimeoutMs = -1; @@ -39,6 +49,34 @@ public class DefaultHttpClientBuilder private static final OkHttpMultiDomainInterceptor multiDomainInterceptor = new OkHttpMultiDomainInterceptor(); + private CloseableHttpClient initDefaultApacheHttpClient() { + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setMaxTotal(MAX_IDLE_CONNECTIONS); + connectionManager.setDefaultMaxPerRoute(MAX_IDLE_CONNECTIONS); + + RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); + + if (connectTimeoutMs >= 0) { + requestConfigBuilder.setConnectTimeout(connectTimeoutMs); + } + if (readTimeoutMs >= 0) { + requestConfigBuilder.setSocketTimeout(readTimeoutMs); + } + if (proxy != null) { + requestConfigBuilder.setProxy(new HttpHost(proxy.address().toString())); + } + + return HttpClientBuilder.create() + .setConnectionManager(connectionManager) + .setDefaultRequestConfig(requestConfigBuilder.build()) + .build(); + } + + public DefaultHttpClientBuilder useApacheHttpClient() { + this.useApacheHttpClient = true; + return this; +} + /** * 复制工厂,复制一个当前对象 * @@ -50,6 +88,7 @@ public DefaultHttpClientBuilder newInstance() { result.credential = this.credential; result.validator = this.validator; result.customizeOkHttpClient = this.customizeOkHttpClient; + result.customizeApacheHttpClient = this.customizeApacheHttpClient; result.readTimeoutMs = this.readTimeoutMs; result.writeTimeoutMs = this.writeTimeoutMs; result.connectTimeoutMs = this.connectTimeoutMs; @@ -122,6 +161,19 @@ public DefaultHttpClientBuilder validator(Validator validator) { */ public DefaultHttpClientBuilder okHttpClient(okhttp3.OkHttpClient okHttpClient) { this.customizeOkHttpClient = okHttpClient; + this.useApacheHttpClient = false; + return this; + } + + /** + * 设置 appacheHttpClient 若设置该参数,会覆盖client中的原有配置 + * + * @param apacheHttpClient 用户自定义的apacheHttpClient + * @return defaultHttpClientBuilder + */ + public DefaultHttpClientBuilder apacheHttpClient(CloseableHttpClient apacheHttpClient) { + this.customizeApacheHttpClient = apacheHttpClient; + this.useApacheHttpClient = true; return this; } @@ -154,15 +206,7 @@ public DefaultHttpClientBuilder disableRetryOnConnectionFailure() { return this; } - /** - * 构建默认HttpClient - * - * @return httpClient - */ - @Override - public AbstractHttpClient build() { - requireNonNull(credential); - requireNonNull(validator); + private AbstractHttpClient buildOkHttpClient() { okhttp3.OkHttpClient.Builder okHttpClientBuilder = (customizeOkHttpClient == null ? defaultOkHttpClient : customizeOkHttpClient).newBuilder(); if (connectTimeoutMs >= 0) { @@ -185,4 +229,27 @@ public AbstractHttpClient build() { } return new OkHttpClientAdapter(credential, validator, okHttpClientBuilder.build()); } + + private AbstractHttpClient buildApacheHttpClient() { + CloseableHttpClient httpclient = customizeApacheHttpClient == null ? initDefaultApacheHttpClient() : customizeApacheHttpClient; + // 每次都会创建一个 httpclient 实例,和 okhttp 不同 + // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client that shares the same connection po)ol, thread pools, and configuration. + return new ApacheHttpClientAdapter(credential, validator, httpclient); + } + + /** + * 构建默认HttpClient + * + * @return httpClient + */ + @Override + public AbstractHttpClient build() { + requireNonNull(credential); + requireNonNull(validator); + + if (useApacheHttpClient) { + return buildApacheHttpClient(); + } + return buildOkHttpClient(); + } } diff --git a/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java b/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java new file mode 100644 index 00000000..0b92e880 --- /dev/null +++ b/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java @@ -0,0 +1,169 @@ +package com.wechat.pay.java.core.http.apache; + +import static java.util.Objects.requireNonNull; +import static org.apache.http.entity.ContentType.APPLICATION_JSON; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPatch; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import com.wechat.pay.java.core.exception.HttpException; +import com.wechat.pay.java.core.exception.MalformedMessageException; +import com.wechat.pay.java.core.exception.ServiceException; +import com.wechat.pay.java.core.http.AbstractHttpClient; +import com.wechat.pay.java.core.http.FileRequestBody; +import com.wechat.pay.java.core.http.HttpRequest; +import com.wechat.pay.java.core.http.JsonRequestBody; +import com.wechat.pay.java.core.http.OriginalResponse; + +public class ApacheHttpClientAdapter extends AbstractHttpClient { + + private static final Logger logger = LoggerFactory.getLogger(ApacheHttpClientAdapter.class); + private static final String META_NAME = "meta"; + private static final String FILE_NAME = "file"; + + private final CloseableHttpClient apacheHttpClient; + + public ApacheHttpClientAdapter(Credential credential, Validator validator, CloseableHttpClient client) { + super(credential, validator); + this.apacheHttpClient = requireNonNull(client); + } + + @Override + protected String getHttpClientInfo() { + return "apachehttp/" + apacheHttpClient.getClass().getPackage().getImplementationVersion(); + } + + @Override + public OriginalResponse innerExecute(HttpRequest wechatPayRequest) { + try { + CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute(buildApacheHttpRequest(wechatPayRequest)); + return assembleOriginalResponse(wechatPayRequest, apacheHttpResponse); + } catch (IOException e) { + throw new HttpException(wechatPayRequest, e); + } + } + + private org.apache.http.client.methods.HttpUriRequest buildApacheHttpRequest(HttpRequest wechatPayRequest) { + String url = wechatPayRequest.getUrl().toString(); + org.apache.http.client.methods.HttpUriRequest apacheHttpRequest; + + switch (wechatPayRequest.getHttpMethod().name()) { + case "GET": + apacheHttpRequest = new HttpGet(url); + break; + case "POST": + apacheHttpRequest = new HttpPost(url); + ((HttpPost) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); + break; + case "PUT": + apacheHttpRequest = new HttpPut(url); + ((HttpPut) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); + break; + case "PATCH": + apacheHttpRequest = new HttpPatch(url); + ((HttpPatch) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); + break; + case "DELETE": + apacheHttpRequest = new HttpDelete(url); + break; + default: + throw new IllegalArgumentException("Unsupported HTTP method: " + wechatPayRequest.getHttpMethod().name()); + } + Map headers = wechatPayRequest.getHeaders().getHeaders(); + headers.forEach(apacheHttpRequest::addHeader); + return apacheHttpRequest; + } + + private HttpEntity buildApacheHttpEntity(com.wechat.pay.java.core.http.RequestBody wechatPayRequestBody) { + // 处理空请求体的情况 + if (wechatPayRequestBody == null) { + return new StringEntity("", ""); + } + + if (wechatPayRequestBody instanceof JsonRequestBody) { + return new StringEntity( + ((JsonRequestBody) wechatPayRequestBody).getBody(), + ContentType.create(wechatPayRequestBody.getContentType())); + } + if (wechatPayRequestBody instanceof FileRequestBody) { + FileRequestBody fileRequestBody = (FileRequestBody) wechatPayRequestBody; + MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); + entityBuilder.setMode(HttpMultipartMode.RFC6532); + entityBuilder.addTextBody(META_NAME, fileRequestBody.getMeta(), APPLICATION_JSON); + entityBuilder.addBinaryBody(FILE_NAME, fileRequestBody.getFile(), ContentType.create(fileRequestBody.getContentType()), fileRequestBody.getFileName()); + return entityBuilder.build(); + } + logger.error( + "When an http request is sent and the apache request body is constructed, the requestBody parameter" + + " type cannot be found,requestBody class name[{}]", + wechatPayRequestBody.getClass().getName()); + return null; + } + + private OriginalResponse assembleOriginalResponse(HttpRequest wechatPayRequest, CloseableHttpResponse apacheHttpResponse) throws IOException { + Map responseHeaders = assembleResponseHeader(apacheHttpResponse); + HttpEntity entity = apacheHttpResponse.getEntity(); + try { + String responseBody = entity != null ? EntityUtils.toString(entity) : null; + return new OriginalResponse.Builder() + .request(wechatPayRequest) + .headers(responseHeaders) + .statusCode(apacheHttpResponse.getStatusLine().getStatusCode()) + .contentType(entity != null ? entity.getContentType().getValue() : null) + .body(responseBody) + .build(); + } catch (IOException e) { + throw new MalformedMessageException( + String.format( + "Assemble OriginalResponse,get responseBody failed.%nHttpRequest[%s]", + wechatPayRequest)); + } + } + + private Map assembleResponseHeader(CloseableHttpResponse apacheHttpResponse) { + Map responseHeaders = new ConcurrentHashMap<>(); + Header[] headers = apacheHttpResponse.getAllHeaders(); + for (Header header : headers) { + responseHeaders.put(header.getName(), header.getValue()); + } + return responseHeaders; + } + + @Override + protected InputStream innerDownload(HttpRequest httpRequest) { + try { + CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute(buildApacheHttpRequest(httpRequest)); + if (isInvalidHttpCode(apacheHttpResponse.getStatusLine().getStatusCode())) { + throw new ServiceException(httpRequest, apacheHttpResponse.getStatusLine().getStatusCode(), ""); + } + InputStream responseBodyStream = null; + if (apacheHttpResponse.getEntity() != null) { + responseBodyStream = apacheHttpResponse.getEntity().getContent(); + } + return responseBodyStream; + } catch (IOException e) { + throw new HttpException(httpRequest, e); + } + } +} diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java new file mode 100644 index 00000000..4e5dd1c9 --- /dev/null +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java @@ -0,0 +1,1541 @@ +package com.wechat.pay.java.core.http; + +import java.io.IOException; +import java.net.URI; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.HttpException; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.HttpResponseInterceptor; +import org.apache.http.HttpStatus; +import org.apache.http.ProtocolVersion; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicStatusLine; +import org.apache.http.protocol.HttpContext; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import static com.wechat.pay.java.core.http.Constant.AUTHORIZATION; +import static com.wechat.pay.java.core.http.Constant.OS; +import static com.wechat.pay.java.core.http.Constant.USER_AGENT; +import static com.wechat.pay.java.core.http.Constant.USER_AGENT_FORMAT; +import static com.wechat.pay.java.core.http.Constant.VERSION; +import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; +import static com.wechat.pay.java.core.model.TestConfig.MERCHANT_ID; +import static com.wechat.pay.java.core.model.TestConfig.RESOURCES_DIR; +import com.wechat.pay.java.core.model.TestServiceResponse; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.io.InputStream; +import com.wechat.pay.java.core.util.IOUtil; + + +public class ApacheHttpClientAdapterTest { + + private static final String APACHE_HTTP_CLIENT_MOCK_DATA_DIR = RESOURCES_DIR + "/http"; + private static final String URL = "https://api.mch.weixin.qq.com/v3/certificates"; + private static final String RESPONSE_JSON_KEY = "request_id"; + private static final String RESPONSE_JSON_VALUE = "123"; + private static final String RESPONSE_JSON = + "{\"" + RESPONSE_JSON_KEY + "\":\"" + RESPONSE_JSON_VALUE + "\"}"; + private static final String REQUEST_HEADER_KEY = "request-header-key"; + private static final String REQUEST_HEADER_VALUE = "request-header-value"; + private static final String REQUEST_BODY_KEY = "request-body-key"; + private static final String REQUEST_BODY_VALUE = "request-body-value"; + private static final JsonRequestBody JSON_REQUEST_BODY = + new JsonRequestBody.Builder() + .body("{\"" + REQUEST_BODY_KEY + "\":\"" + REQUEST_BODY_VALUE + "\"}") + .build(); + + private static final String RESPONSE_HEADER_KEY = "response-header-key"; + private static final String RESPONSE_HEADER_VALUE = "response-header-value"; + + private static final String FAKE_AUTHORIZATION = "fake-authorization"; + private static HttpHeaders requestHeaders; + + @BeforeClass + public static void init() { + requestHeaders = new HttpHeaders(); + requestHeaders.addHeader(REQUEST_HEADER_KEY, REQUEST_HEADER_VALUE); + } + + @Test + public void testExecuteSendGetRequest() { + Credential executeSendGetCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.GET.name(), httpMethod); + Assert.assertEquals("", signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendGetRequestValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendGetCredential.getClass().getSimpleName(), + executeSendGetRequestValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + String executeSendGetMethod = request.getRequestLine().getMethod(); + Assert.assertEquals(executeSendGetMethod, HttpMethod.GET.name()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals(FAKE_AUTHORIZATION, getHeaderValue(headers, AUTHORIZATION)); + Assert.assertEquals( + executeSendGetCredential.getAuthorization(URI.create(URL), executeSendGetMethod, ""), + getHeaderValue(headers, AUTHORIZATION)); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + CloseableHttpClient httpclient = + HttpClients.custom().addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build(); + + HttpClient executeSendGetHttpClient = + new DefaultHttpClientBuilder() + .credential(executeSendGetCredential) + .validator(executeSendGetRequestValidator) + .apacheHttpClient(httpclient) + .build(); + + com.wechat.pay.java.core.http.HttpRequest executeSendGetHttpRequest = + new com.wechat.pay.java.core.http.HttpRequest.Builder() + .httpMethod(HttpMethod.GET) + .url(URL) + .headers(requestHeaders) + .build(); + + com.wechat.pay.java.core.http.HttpResponse executeSendGetResponse = + executeSendGetHttpClient.execute(executeSendGetHttpRequest, TestServiceResponse.class); + + Assert.assertEquals(4, executeSendGetResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendGetResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendGetResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendGetResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendGetResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendGetResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendGetResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendGetResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testExecuteSendPostReqWithJsonBody() throws IOException { + Credential executeSendPostCredential = new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.POST.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + + Validator executeSendPostValidator = new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals(RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPostCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentType().getValue(), reqEntity.getContentType().getValue()); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient executeSendPostHttpClient = new DefaultHttpClientBuilder() + .credential(executeSendPostCredential) + .validator(executeSendPostValidator) + .apacheHttpClient(httpClient) + .build(); + + + HttpRequest executeSendPostHttpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.POST) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); + + + HttpResponse executeSendPostResponse = + executeSendPostHttpClient.execute(executeSendPostHttpRequest, TestServiceResponse.class); + Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPostResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPostResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendPostResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPostResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPostResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPostResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPostResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testExecuteSendPostReqWithFileBody() throws IOException { + String imageName = "test_image.jpg"; + String imagePath = APACHE_HTTP_CLIENT_MOCK_DATA_DIR + "/" + imageName; + InputStream inputStream = Files.newInputStream(Paths.get(imagePath)); + FileRequestBody requestBody = + new FileRequestBody.Builder() + .meta("meta") + .fileName(imageName) + .file(IOUtil.toByteArray(inputStream)) + .build(); + + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.RFC6532); + builder.addTextBody("meta", "meta"); + builder.addBinaryBody("file", requestBody.getFile(), ContentType.create(requestBody.getContentType()), imageName); + HttpEntity multipartEntity = builder.build(); + Credential executeSendPostWithFileCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.POST.name(), httpMethod); + System.out.println("signBody=" + signBody); + Assert.assertEquals("meta", signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendPostWithFileValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendPostWithFileCredential.getClass().getSimpleName(), + executeSendPostWithFileValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPostWithFileCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + "meta"), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + // apache multipart entity content length 每次创建不一样,不做校验 + // Assert.assertEquals(multipartEntity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + System.out.println("process response: " + response); + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient executeSendPostWithFileHttpClient = new DefaultHttpClientBuilder() + .credential(executeSendPostWithFileCredential) + .validator(executeSendPostWithFileValidator) + .apacheHttpClient(httpClient) + .build(); + + + HttpRequest executeSendPostHttpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.POST) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); + + HttpResponse executeSendPostWithFileResponse = + executeSendPostWithFileHttpClient.post( + requestHeaders, URL, requestBody, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPostWithFileResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPostWithFileResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPostWithFileResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.POST, executeSendPostWithFileResponse.getRequest().getHttpMethod()); + Assert.assertEquals(requestBody, executeSendPostWithFileResponse.getRequest().getBody()); + Assert.assertEquals(URL, executeSendPostWithFileResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPostWithFileResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPostWithFileResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPostWithFileResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPostWithFileResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPostWithFileResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testExecuteSendPutRequest() throws IOException { + Credential executeSendPutCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PUT.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendPutValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendPutCredential.getClass().getSimpleName(), + executeSendPutValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PUT.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPutCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + .credential(executeSendPutCredential) + .validator(executeSendPutValidator) + .apacheHttpClient(httpClient) + .build(); + + + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.PUT) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); + + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testExecuteSendPatchRequest() throws IOException { + Credential executeSendPatchCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PATCH.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendPatchValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendPatchCredential.getClass().getSimpleName(), + executeSendPatchValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PATCH.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPatchCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + .credential(executeSendPatchCredential) + .validator(executeSendPatchValidator) + .apacheHttpClient(httpClient) + .build(); + + + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.PATCH) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); + + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.PATCH, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testExecuteSendDeleteRequest() throws IOException { + Credential executeSendDeleteCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendDeleteValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendDeleteCredential.getClass().getSimpleName(), + executeSendDeleteValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.DELETE.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendDeleteCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + .credential(executeSendDeleteCredential) + .validator(executeSendDeleteValidator) + .apacheHttpClient(httpClient) + .build(); + + + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.DELETE) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); + + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } + + + @Test + public void testGet() { + Credential getCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.GET.name(), httpMethod); + Assert.assertEquals("", signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator getHttpValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + getCredential.getClass().getSimpleName(), + getHttpValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + String getMethod = request.getRequestLine().getMethod(); + Assert.assertEquals(getMethod, HttpMethod.GET.name()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals(FAKE_AUTHORIZATION, getHeaderValue(headers, AUTHORIZATION)); + Assert.assertEquals( + getCredential.getAuthorization(URI.create(URL), getMethod, ""), + getHeaderValue(headers, AUTHORIZATION)); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + CloseableHttpClient httpclient = + HttpClients.custom().addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build(); + + HttpClient getHttpClient = + new DefaultHttpClientBuilder() + .credential(getCredential) + .validator(getHttpValidator) + .apacheHttpClient(httpclient) + .build(); + + com.wechat.pay.java.core.http.HttpResponse executeSendGetResponse = + getHttpClient.get(requestHeaders, URL, TestServiceResponse.class); + + Assert.assertEquals(4, executeSendGetResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendGetResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendGetResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendGetResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendGetResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendGetResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendGetResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendGetResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testPost() throws IOException { + Credential postCredential = new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.POST.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator postValidator = new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals(RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + postCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentType().getValue(), reqEntity.getContentType().getValue()); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient postHttpClient = new DefaultHttpClientBuilder() + .credential(postCredential) + .validator(postValidator) + .apacheHttpClient(httpClient) + .build(); + + HttpResponse executeSendPostResponse = + postHttpClient.post(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); + Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPostResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPostResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendPostResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPostResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPostResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPostResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPostResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testPatch() throws IOException { + Credential patchCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PATCH.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator patchValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + patchCredential.getClass().getSimpleName(), + patchValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PATCH.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + patchCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient patchHttpClient = new DefaultHttpClientBuilder() + .credential(patchCredential) + .validator(patchValidator) + .apacheHttpClient(httpClient) + .build(); + + HttpResponse executeSendPutResponse = + patchHttpClient.patch(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.PATCH, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } + + + @Test + public void testPut() throws IOException { + Credential putCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PUT.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator putValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + putCredential.getClass().getSimpleName(), + putValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PUT.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + putCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient putHttpClient = new DefaultHttpClientBuilder() + .credential(putCredential) + .validator(putValidator) + .apacheHttpClient(httpClient) + .build(); + + HttpResponse executeSendPutResponse = + putHttpClient.put(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } + + + @Test + public void testDelete() throws IOException { + Credential executeSendDeleteCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendDeleteValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendDeleteCredential.getClass().getSimpleName(), + executeSendDeleteValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + Assert.assertEquals(HttpMethod.DELETE.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendDeleteCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[]{header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = HttpClients.custom(). + addInterceptorFirst(interceptor). + addInterceptorLast(responseInterceptor).build(); + + HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + .credential(executeSendDeleteCredential) + .validator(executeSendDeleteValidator) + .apacheHttpClient(httpClient) + .build(); + + + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.DELETE) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); + + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); + + + Assert.assertEquals( + 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } + +} diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java new file mode 100644 index 00000000..767af316 --- /dev/null +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java @@ -0,0 +1,79 @@ +package com.wechat.pay.java.core.http; + +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import java.net.URI; + +public class ApacheHttpClientAdapterV2Test implements HttpClientTest { + @Override + public HttpClient createHttpClient() { + Credential credential = + new Credential() { + @Override + public String getSchema() { + return "foo"; + } + + @Override + public String getMerchantId() { + return "1234567890"; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + return "bar"; + } + }; + + Validator validator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + + return new DefaultHttpClientBuilder().credential(credential).validator(validator).useApacheHttpClient().build(); + } + + @Override + public HttpClient createFalseValidationHttpClient() { + Credential credential = + new Credential() { + @Override + public String getSchema() { + return "foo"; + } + + @Override + public String getMerchantId() { + return "1234567890"; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + return "bar"; + } + }; + + Validator validator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + return false; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + + return new DefaultHttpClientBuilder().credential(credential).validator(validator).useApacheHttpClient().build(); + } +} diff --git a/core/src/test/java/com/wechat/pay/java/core/http/HttpClientTest.java b/core/src/test/java/com/wechat/pay/java/core/http/HttpClientTest.java index f1baec82..1f6b5ef6 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/HttpClientTest.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/HttpClientTest.java @@ -235,7 +235,7 @@ default void testDownload_IllegalArgumentException() { } @ParameterizedTest - @ValueSource(ints = {199, 300}) + @ValueSource(ints = {400, 300}) default void testDownload_ServiceException(int responseCode) throws IOException { HttpClient client = createHttpClient(); MockWebServer server = new MockWebServer(); diff --git a/gradle.properties b/gradle.properties index a0a01163..7c174b5b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,6 +5,7 @@ slf4jVersion=1.7.36 junitVersion=4.13.2 junit5Version=5.9.1 okhttpVersion=4.10.0 +apachehttpVersion=4.5.13 gsonVersion=2.9.1 mockitoCoreVersion=5.12.0 awaitilityVersion=4.2.0 From f1cd9d223776dc1771c2bdf3e765f6cfe55049ad Mon Sep 17 00:00:00 2001 From: masutangu Date: Mon, 25 Nov 2024 19:47:32 +0800 Subject: [PATCH 02/10] =?UTF-8?q?=E6=96=B0=E5=A2=9EapacheHttpClientBuilder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/http/ApacheHttpClientBuilder.java | 113 ++++++++++++++++++ .../core/http/DefaultHttpClientBuilder.java | 89 ++------------ .../http/ApacheHttpClientAdapterTest.java | 112 +++++++++-------- .../http/ApacheHttpClientAdapterV2Test.java | 4 +- .../http/ApacheHttpClientBuilderTest.java | 100 ++++++++++++++++ 5 files changed, 280 insertions(+), 138 deletions(-) create mode 100644 core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java create mode 100644 core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java diff --git a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java new file mode 100644 index 00000000..c109298c --- /dev/null +++ b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java @@ -0,0 +1,113 @@ +package com.wechat.pay.java.core.http; + +import java.net.Proxy; +import static java.util.Objects.requireNonNull; +import java.util.concurrent.TimeUnit; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; + +import com.wechat.pay.java.core.Config; +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import com.wechat.pay.java.core.http.apache.ApacheHttpClientAdapter; +import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; +import com.wechat.pay.java.core.http.okhttp.OkHttpMultiDomainInterceptor; + +/** 默认HttpClient构造器 */ +public class ApacheHttpClientBuilder + implements AbstractHttpClientBuilder { + + private Credential credential; + private Validator validator; + + + private CloseableHttpClient customizeApacheHttpClient; + private static final OkHttpMultiDomainInterceptor multiDomainInterceptor = + new OkHttpMultiDomainInterceptor(); + + static PoolingHttpClientConnectionManager apacheHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); + + + private CloseableHttpClient initDefaultApacheHttpClient() { + return HttpClientBuilder.create() + .setConnectionManager(apacheHttpClientConnectionManager) + .setConnectionManagerShared(true) + .build(); + } + + /** + * 复制工厂,复制一个当前对象 + * + * @return 对象的副本 + */ + @Override + public ApacheHttpClientBuilder newInstance() { + ApacheHttpClientBuilder result = new ApacheHttpClientBuilder(); + result.credential = this.credential; + result.validator = this.validator; + result.customizeApacheHttpClient = this.customizeApacheHttpClient; + return result; + } + + /** + * 设置凭据生成器 + * + * @param credential 凭据生成器 + * @return defaultHttpClientBuilder + */ + @Override + public ApacheHttpClientBuilder credential(Credential credential) { + this.credential = credential; + return this; + } + + /** + * 设置验证器 + * + * @param validator 验证器 + * @return defaultHttpClientBuilder + */ + @Override + public ApacheHttpClientBuilder validator(Validator validator) { + this.validator = validator; + return this; + } + + /** + * 设置 appacheHttpClient 若设置该client,则忽略其他参数 + * + * @param apacheHttpClient 用户自定义的apacheHttpClient + * @return defaultHttpClientBuilder + */ + public ApacheHttpClientBuilder apacheHttpClient(CloseableHttpClient apacheHttpClient) { + this.customizeApacheHttpClient = apacheHttpClient; + return this; + } + + public ApacheHttpClientBuilder config(Config config) { + requireNonNull(config); + this.credential = config.createCredential(); + this.validator = config.createValidator(); + return this; + } + + /** + * 构建默认HttpClient + * + * @return httpClient + */ + @Override + public AbstractHttpClient build() { + requireNonNull(credential); + requireNonNull(validator); + + CloseableHttpClient httpclient = customizeApacheHttpClient == null ? initDefaultApacheHttpClient() : customizeApacheHttpClient; + // 每次都会创建一个 httpclient 实例,和 okhttp 不同 + // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client that shares the same connection po)ol, thread pools, and configuration. + return new ApacheHttpClientAdapter(credential, validator, httpclient); + } +} diff --git a/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java index d4e648a5..af81a2c2 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/DefaultHttpClientBuilder.java @@ -1,22 +1,14 @@ package com.wechat.pay.java.core.http; -import java.net.Proxy; import static java.util.Objects.requireNonNull; -import java.util.concurrent.TimeUnit; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.auth.Credential; import com.wechat.pay.java.core.auth.Validator; -import com.wechat.pay.java.core.http.apache.ApacheHttpClientAdapter; import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; import com.wechat.pay.java.core.http.okhttp.OkHttpMultiDomainInterceptor; - +import java.net.Proxy; +import java.util.concurrent.TimeUnit; import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; @@ -38,8 +30,6 @@ public class DefaultHttpClientBuilder new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS)) .build(); private okhttp3.OkHttpClient customizeOkHttpClient; - private CloseableHttpClient customizeApacheHttpClient; - private boolean useApacheHttpClient = false; // private int readTimeoutMs = -1; private int writeTimeoutMs = -1; private int connectTimeoutMs = -1; @@ -49,34 +39,6 @@ public class DefaultHttpClientBuilder private static final OkHttpMultiDomainInterceptor multiDomainInterceptor = new OkHttpMultiDomainInterceptor(); - private CloseableHttpClient initDefaultApacheHttpClient() { - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setMaxTotal(MAX_IDLE_CONNECTIONS); - connectionManager.setDefaultMaxPerRoute(MAX_IDLE_CONNECTIONS); - - RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); - - if (connectTimeoutMs >= 0) { - requestConfigBuilder.setConnectTimeout(connectTimeoutMs); - } - if (readTimeoutMs >= 0) { - requestConfigBuilder.setSocketTimeout(readTimeoutMs); - } - if (proxy != null) { - requestConfigBuilder.setProxy(new HttpHost(proxy.address().toString())); - } - - return HttpClientBuilder.create() - .setConnectionManager(connectionManager) - .setDefaultRequestConfig(requestConfigBuilder.build()) - .build(); - } - - public DefaultHttpClientBuilder useApacheHttpClient() { - this.useApacheHttpClient = true; - return this; -} - /** * 复制工厂,复制一个当前对象 * @@ -88,7 +50,6 @@ public DefaultHttpClientBuilder newInstance() { result.credential = this.credential; result.validator = this.validator; result.customizeOkHttpClient = this.customizeOkHttpClient; - result.customizeApacheHttpClient = this.customizeApacheHttpClient; result.readTimeoutMs = this.readTimeoutMs; result.writeTimeoutMs = this.writeTimeoutMs; result.connectTimeoutMs = this.connectTimeoutMs; @@ -161,19 +122,6 @@ public DefaultHttpClientBuilder validator(Validator validator) { */ public DefaultHttpClientBuilder okHttpClient(okhttp3.OkHttpClient okHttpClient) { this.customizeOkHttpClient = okHttpClient; - this.useApacheHttpClient = false; - return this; - } - - /** - * 设置 appacheHttpClient 若设置该参数,会覆盖client中的原有配置 - * - * @param apacheHttpClient 用户自定义的apacheHttpClient - * @return defaultHttpClientBuilder - */ - public DefaultHttpClientBuilder apacheHttpClient(CloseableHttpClient apacheHttpClient) { - this.customizeApacheHttpClient = apacheHttpClient; - this.useApacheHttpClient = true; return this; } @@ -206,7 +154,15 @@ public DefaultHttpClientBuilder disableRetryOnConnectionFailure() { return this; } - private AbstractHttpClient buildOkHttpClient() { + /** + * 构建默认HttpClient + * + * @return httpClient + */ + @Override + public AbstractHttpClient build() { + requireNonNull(credential); + requireNonNull(validator); okhttp3.OkHttpClient.Builder okHttpClientBuilder = (customizeOkHttpClient == null ? defaultOkHttpClient : customizeOkHttpClient).newBuilder(); if (connectTimeoutMs >= 0) { @@ -229,27 +185,4 @@ private AbstractHttpClient buildOkHttpClient() { } return new OkHttpClientAdapter(credential, validator, okHttpClientBuilder.build()); } - - private AbstractHttpClient buildApacheHttpClient() { - CloseableHttpClient httpclient = customizeApacheHttpClient == null ? initDefaultApacheHttpClient() : customizeApacheHttpClient; - // 每次都会创建一个 httpclient 实例,和 okhttp 不同 - // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client that shares the same connection po)ol, thread pools, and configuration. - return new ApacheHttpClientAdapter(credential, validator, httpclient); - } - - /** - * 构建默认HttpClient - * - * @return httpClient - */ - @Override - public AbstractHttpClient build() { - requireNonNull(credential); - requireNonNull(validator); - - if (useApacheHttpClient) { - return buildApacheHttpClient(); - } - return buildOkHttpClient(); - } } diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java index 4e5dd1c9..d0fe7cff 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java @@ -28,7 +28,6 @@ import com.wechat.pay.java.core.auth.Validator; import static com.wechat.pay.java.core.http.Constant.AUTHORIZATION; import static com.wechat.pay.java.core.http.Constant.OS; -import static com.wechat.pay.java.core.http.Constant.USER_AGENT; import static com.wechat.pay.java.core.http.Constant.USER_AGENT_FORMAT; import static com.wechat.pay.java.core.http.Constant.VERSION; import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; @@ -36,7 +35,6 @@ import static com.wechat.pay.java.core.model.TestConfig.RESOURCES_DIR; import com.wechat.pay.java.core.model.TestServiceResponse; -import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.io.InputStream; @@ -163,9 +161,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) }; CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build(); - HttpClient executeSendGetHttpClient = - new DefaultHttpClientBuilder() + new ApacheHttpClientBuilder() .credential(executeSendGetCredential) .validator(executeSendGetRequestValidator) .apacheHttpClient(httpclient) @@ -253,7 +250,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); HttpEntity entity = new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); @@ -276,7 +273,6 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -290,7 +286,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient executeSendPostHttpClient = new DefaultHttpClientBuilder() + HttpClient executeSendPostHttpClient = new ApacheHttpClientBuilder() .credential(executeSendPostCredential) .validator(executeSendPostValidator) .apacheHttpClient(httpClient) @@ -305,7 +301,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) .body(JSON_REQUEST_BODY) .build(); - + HttpResponse executeSendPostResponse = executeSendPostHttpClient.execute(executeSendPostHttpRequest, TestServiceResponse.class); Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); @@ -335,12 +331,12 @@ public void testExecuteSendPostReqWithFileBody() throws IOException { .fileName(imageName) .file(IOUtil.toByteArray(inputStream)) .build(); - + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.RFC6532); builder.addTextBody("meta", "meta"); builder.addBinaryBody("file", requestBody.getFile(), ContentType.create(requestBody.getContentType()), imageName); - HttpEntity multipartEntity = builder.build(); + HttpEntity multipartEntity = builder.build(); Credential executeSendPostWithFileCredential = new Credential() { @Override @@ -406,7 +402,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); // apache multipart entity content length 每次创建不一样,不做校验 // Assert.assertEquals(multipartEntity.getContentLength(), reqEntity.getContentLength()); } @@ -427,7 +423,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) System.out.println("process response: " + response); Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -441,7 +437,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient executeSendPostWithFileHttpClient = new DefaultHttpClientBuilder() + HttpClient executeSendPostWithFileHttpClient = new ApacheHttpClientBuilder() .credential(executeSendPostWithFileCredential) .validator(executeSendPostWithFileValidator) .apacheHttpClient(httpClient) @@ -459,8 +455,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPostWithFileResponse = executeSendPostWithFileHttpClient.post( requestHeaders, URL, requestBody, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPostWithFileResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -516,7 +512,7 @@ public boolean validate(HttpHeaders responseHeaders, String body) { Assert.assertEquals(RESPONSE_JSON, body); return true; } - + @Override public String getSerialNumber() { return ""; @@ -549,7 +545,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); HttpEntity entity = new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); @@ -571,7 +567,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -585,7 +581,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() .credential(executeSendPutCredential) .validator(executeSendPutValidator) .apacheHttpClient(httpClient) @@ -602,8 +598,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPutResponse = executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -623,7 +619,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } + } @Test public void testExecuteSendPatchRequest() throws IOException { @@ -692,7 +688,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); HttpEntity entity = new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); @@ -714,7 +710,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -728,7 +724,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() .credential(executeSendPatchCredential) .validator(executeSendPatchValidator) .apacheHttpClient(httpClient) @@ -745,8 +741,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPutResponse = executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -766,7 +762,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } + } @Test public void testExecuteSendDeleteRequest() throws IOException { @@ -848,7 +844,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -862,7 +858,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() .credential(executeSendDeleteCredential) .validator(executeSendDeleteValidator) .apacheHttpClient(httpClient) @@ -879,8 +875,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPutResponse = executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -900,9 +896,9 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - - + } + + @Test public void testGet() { Credential getCredential = @@ -993,9 +989,9 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) }; CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build(); - + HttpClient getHttpClient = - new DefaultHttpClientBuilder() + new ApacheHttpClientBuilder() .credential(getCredential) .validator(getHttpValidator) .apacheHttpClient(httpclient) @@ -1075,7 +1071,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); HttpEntity entity = new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); @@ -1098,7 +1094,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -1112,7 +1108,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient postHttpClient = new DefaultHttpClientBuilder() + HttpClient postHttpClient = new ApacheHttpClientBuilder() .credential(postCredential) .validator(postValidator) .apacheHttpClient(httpClient) @@ -1202,7 +1198,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); HttpEntity entity = new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); @@ -1224,7 +1220,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -1238,7 +1234,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient patchHttpClient = new DefaultHttpClientBuilder() + HttpClient patchHttpClient = new ApacheHttpClientBuilder() .credential(patchCredential) .validator(patchValidator) .apacheHttpClient(httpClient) @@ -1246,8 +1242,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPutResponse = patchHttpClient.patch(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -1267,7 +1263,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } + } @Test @@ -1336,7 +1332,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity reqEntity = entityRequest.getEntity(); HttpEntity entity = new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); @@ -1358,7 +1354,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -1372,7 +1368,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient putHttpClient = new DefaultHttpClientBuilder() + HttpClient putHttpClient = new ApacheHttpClientBuilder() .credential(putCredential) .validator(putValidator) .apacheHttpClient(httpClient) @@ -1380,8 +1376,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPutResponse = putHttpClient.put(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -1401,7 +1397,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } + } @Test @@ -1484,7 +1480,7 @@ private String getHeaderValue(Header[] headers, String name) { public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); response.setHeaders(new Header[]{header}); - + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; @@ -1498,7 +1494,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) addInterceptorFirst(interceptor). addInterceptorLast(responseInterceptor).build(); - HttpClient executeSendPutHttpClient = new DefaultHttpClientBuilder() + HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() .credential(executeSendDeleteCredential) .validator(executeSendDeleteValidator) .apacheHttpClient(httpClient) @@ -1515,8 +1511,8 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpResponse executeSendPutResponse = executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - + + Assert.assertEquals( 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( @@ -1536,6 +1532,6 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - + } + } diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java index 767af316..2e9131d9 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterV2Test.java @@ -38,7 +38,7 @@ public String getSerialNumber() { } }; - return new DefaultHttpClientBuilder().credential(credential).validator(validator).useApacheHttpClient().build(); + return new ApacheHttpClientBuilder().credential(credential).validator(validator).build(); } @Override @@ -74,6 +74,6 @@ public String getSerialNumber() { } }; - return new DefaultHttpClientBuilder().credential(credential).validator(validator).useApacheHttpClient().build(); + return new ApacheHttpClientBuilder().credential(credential).validator(validator).build(); } } diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java new file mode 100644 index 00000000..b86462a9 --- /dev/null +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java @@ -0,0 +1,100 @@ +package com.wechat.pay.java.core.http; + +import com.wechat.pay.java.core.Config; +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import com.wechat.pay.java.core.cipher.PrivacyDecryptor; +import com.wechat.pay.java.core.cipher.PrivacyEncryptor; +import com.wechat.pay.java.core.cipher.Signer; +import okhttp3.OkHttpClient; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.jupiter.api.Test; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.Proxy.Type; +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ApacheHttpClientBuilderTest { + + Credential credential = + new Credential() { + @Override + public String getSchema() { + return "schema"; + } + + @Override + public String getMerchantId() { + return "123456"; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + return "authorization"; + } + }; + + Validator validator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + + CloseableHttpClient apacheHttpClient = HttpClientBuilder.create().build(); + + @Test + void buildWithCredentialAndValidator() { + HttpClient httpClient = + new ApacheHttpClientBuilder() + .credential(credential) + .validator(validator) + .apacheHttpClient(apacheHttpClient) + .build(); + assertNotNull(httpClient); + } + + @Test + void buildWithConfig() { + Config config = + new Config() { + @Override + public PrivacyEncryptor createEncryptor() { + return null; + } + + @Override + public PrivacyDecryptor createDecryptor() { + return null; + } + + @Override + public Credential createCredential() { + return credential; + } + + @Override + public Validator createValidator() { + return validator; + } + + @Override + public Signer createSigner() { + return null; + } + }; + HttpClient httpClient = + new ApacheHttpClientBuilder().config(config).build(); + assertNotNull(httpClient); + } +} From 891d41e668ba5c874b3fb2831377cece0c63821b Mon Sep 17 00:00:00 2001 From: masutangu Date: Mon, 25 Nov 2024 19:49:03 +0800 Subject: [PATCH 03/10] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java index c109298c..0096d778 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java @@ -78,7 +78,7 @@ public ApacheHttpClientBuilder validator(Validator validator) { } /** - * 设置 appacheHttpClient 若设置该client,则忽略其他参数 + * 设置自定义的 appacheHttpClient * * @param apacheHttpClient 用户自定义的apacheHttpClient * @return defaultHttpClientBuilder From 4e05da97ce6a692d5dcdd0135cc0dff81474a9a5 Mon Sep 17 00:00:00 2001 From: masutangu Date: Mon, 25 Nov 2024 20:41:14 +0800 Subject: [PATCH 04/10] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/http/ApacheHttpClientBuilder.java | 18 +++++++---- .../http/apache/ApacheHttpClientAdapter.java | 30 ++++++++++++------- 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java index 0096d778..f8ab5508 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java @@ -1,7 +1,9 @@ package com.wechat.pay.java.core.http; import java.net.Proxy; + import static java.util.Objects.requireNonNull; + import java.util.concurrent.TimeUnit; import org.apache.http.HttpHost; @@ -17,7 +19,9 @@ import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; import com.wechat.pay.java.core.http.okhttp.OkHttpMultiDomainInterceptor; -/** 默认HttpClient构造器 */ +/** + * 默认HttpClient构造器 + */ public class ApacheHttpClientBuilder implements AbstractHttpClientBuilder { @@ -29,7 +33,8 @@ public class ApacheHttpClientBuilder private static final OkHttpMultiDomainInterceptor multiDomainInterceptor = new OkHttpMultiDomainInterceptor(); - static PoolingHttpClientConnectionManager apacheHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); + static PoolingHttpClientConnectionManager apacheHttpClientConnectionManager = + new PoolingHttpClientConnectionManager(); private CloseableHttpClient initDefaultApacheHttpClient() { @@ -78,7 +83,7 @@ public ApacheHttpClientBuilder validator(Validator validator) { } /** - * 设置自定义的 appacheHttpClient + * 设置 appacheHttpClient 若设置该client,则忽略其他参数 * * @param apacheHttpClient 用户自定义的apacheHttpClient * @return defaultHttpClientBuilder @@ -105,9 +110,12 @@ public AbstractHttpClient build() { requireNonNull(credential); requireNonNull(validator); - CloseableHttpClient httpclient = customizeApacheHttpClient == null ? initDefaultApacheHttpClient() : customizeApacheHttpClient; + CloseableHttpClient httpclient = + customizeApacheHttpClient == null ? initDefaultApacheHttpClient() + : customizeApacheHttpClient; // 每次都会创建一个 httpclient 实例,和 okhttp 不同 - // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client that shares the same connection po)ol, thread pools, and configuration. + // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client + // that shares the same connection po)ol, thread pools, and configuration. return new ApacheHttpClientAdapter(credential, validator, httpclient); } } diff --git a/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java b/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java index 0b92e880..c01d78d9 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java @@ -44,7 +44,8 @@ public class ApacheHttpClientAdapter extends AbstractHttpClient { private final CloseableHttpClient apacheHttpClient; - public ApacheHttpClientAdapter(Credential credential, Validator validator, CloseableHttpClient client) { + public ApacheHttpClientAdapter(Credential credential, Validator validator, + CloseableHttpClient client) { super(credential, validator); this.apacheHttpClient = requireNonNull(client); } @@ -57,14 +58,16 @@ protected String getHttpClientInfo() { @Override public OriginalResponse innerExecute(HttpRequest wechatPayRequest) { try { - CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute(buildApacheHttpRequest(wechatPayRequest)); + CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute( + buildApacheHttpRequest(wechatPayRequest)); return assembleOriginalResponse(wechatPayRequest, apacheHttpResponse); } catch (IOException e) { throw new HttpException(wechatPayRequest, e); } } - private org.apache.http.client.methods.HttpUriRequest buildApacheHttpRequest(HttpRequest wechatPayRequest) { + private org.apache.http.client.methods.HttpUriRequest buildApacheHttpRequest( + HttpRequest wechatPayRequest) { String url = wechatPayRequest.getUrl().toString(); org.apache.http.client.methods.HttpUriRequest apacheHttpRequest; @@ -88,14 +91,16 @@ private org.apache.http.client.methods.HttpUriRequest buildApacheHttpRequest(Htt apacheHttpRequest = new HttpDelete(url); break; default: - throw new IllegalArgumentException("Unsupported HTTP method: " + wechatPayRequest.getHttpMethod().name()); + throw new IllegalArgumentException( + "Unsupported HTTP method: " + wechatPayRequest.getHttpMethod().name()); } Map headers = wechatPayRequest.getHeaders().getHeaders(); headers.forEach(apacheHttpRequest::addHeader); return apacheHttpRequest; } - private HttpEntity buildApacheHttpEntity(com.wechat.pay.java.core.http.RequestBody wechatPayRequestBody) { + private HttpEntity buildApacheHttpEntity( + com.wechat.pay.java.core.http.RequestBody wechatPayRequestBody) { // 处理空请求体的情况 if (wechatPayRequestBody == null) { return new StringEntity("", ""); @@ -111,17 +116,20 @@ private HttpEntity buildApacheHttpEntity(com.wechat.pay.java.core.http.RequestBo MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.RFC6532); entityBuilder.addTextBody(META_NAME, fileRequestBody.getMeta(), APPLICATION_JSON); - entityBuilder.addBinaryBody(FILE_NAME, fileRequestBody.getFile(), ContentType.create(fileRequestBody.getContentType()), fileRequestBody.getFileName()); + entityBuilder.addBinaryBody(FILE_NAME, fileRequestBody.getFile(), + ContentType.create(fileRequestBody.getContentType()), fileRequestBody.getFileName()); return entityBuilder.build(); } logger.error( - "When an http request is sent and the apache request body is constructed, the requestBody parameter" + "When an http request is sent and the apache request body is constructed, the requestBody" + + " parameter" + " type cannot be found,requestBody class name[{}]", wechatPayRequestBody.getClass().getName()); return null; } - private OriginalResponse assembleOriginalResponse(HttpRequest wechatPayRequest, CloseableHttpResponse apacheHttpResponse) throws IOException { + private OriginalResponse assembleOriginalResponse(HttpRequest wechatPayRequest, + CloseableHttpResponse apacheHttpResponse) throws IOException { Map responseHeaders = assembleResponseHeader(apacheHttpResponse); HttpEntity entity = apacheHttpResponse.getEntity(); try { @@ -153,9 +161,11 @@ private Map assembleResponseHeader(CloseableHttpResponse apacheH @Override protected InputStream innerDownload(HttpRequest httpRequest) { try { - CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute(buildApacheHttpRequest(httpRequest)); + CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute( + buildApacheHttpRequest(httpRequest)); if (isInvalidHttpCode(apacheHttpResponse.getStatusLine().getStatusCode())) { - throw new ServiceException(httpRequest, apacheHttpResponse.getStatusLine().getStatusCode(), ""); + throw new ServiceException(httpRequest, apacheHttpResponse.getStatusLine().getStatusCode(), + ""); } InputStream responseBodyStream = null; if (apacheHttpResponse.getEntity() != null) { From b5ea2fa684584036b5f3805959c499662315175c Mon Sep 17 00:00:00 2001 From: masutangu Date: Mon, 25 Nov 2024 21:15:42 +0800 Subject: [PATCH 05/10] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/http/ApacheHttpClientBuilder.java | 30 +- .../http/apache/ApacheHttpClientAdapter.java | 96 +- .../http/ApacheHttpClientAdapterTest.java | 2502 +++++++++-------- .../http/ApacheHttpClientBuilderTest.java | 14 +- 4 files changed, 1350 insertions(+), 1292 deletions(-) diff --git a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java index f8ab5508..50782093 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java @@ -1,41 +1,28 @@ package com.wechat.pay.java.core.http; -import java.net.Proxy; - import static java.util.Objects.requireNonNull; -import java.util.concurrent.TimeUnit; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; - import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.auth.Credential; import com.wechat.pay.java.core.auth.Validator; import com.wechat.pay.java.core.http.apache.ApacheHttpClientAdapter; -import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; import com.wechat.pay.java.core.http.okhttp.OkHttpMultiDomainInterceptor; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -/** - * 默认HttpClient构造器 - */ -public class ApacheHttpClientBuilder - implements AbstractHttpClientBuilder { +/** 默认HttpClient构造器 */ +public class ApacheHttpClientBuilder implements AbstractHttpClientBuilder { private Credential credential; private Validator validator; - private CloseableHttpClient customizeApacheHttpClient; private static final OkHttpMultiDomainInterceptor multiDomainInterceptor = new OkHttpMultiDomainInterceptor(); static PoolingHttpClientConnectionManager apacheHttpClientConnectionManager = - new PoolingHttpClientConnectionManager(); - + new PoolingHttpClientConnectionManager(); private CloseableHttpClient initDefaultApacheHttpClient() { return HttpClientBuilder.create() @@ -111,11 +98,12 @@ public AbstractHttpClient build() { requireNonNull(validator); CloseableHttpClient httpclient = - customizeApacheHttpClient == null ? initDefaultApacheHttpClient() + customizeApacheHttpClient == null + ? initDefaultApacheHttpClient() : customizeApacheHttpClient; // 每次都会创建一个 httpclient 实例,和 okhttp 不同 // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client - // that shares the same connection po)ol, thread pools, and configuration. + // that shares the same connection po)ol, thread pools, and configuration. return new ApacheHttpClientAdapter(credential, validator, httpclient); } } diff --git a/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java b/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java index c01d78d9..bb21ba09 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java @@ -3,11 +3,20 @@ import static java.util.Objects.requireNonNull; import static org.apache.http.entity.ContentType.APPLICATION_JSON; +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import com.wechat.pay.java.core.exception.HttpException; +import com.wechat.pay.java.core.exception.MalformedMessageException; +import com.wechat.pay.java.core.exception.ServiceException; +import com.wechat.pay.java.core.http.AbstractHttpClient; +import com.wechat.pay.java.core.http.FileRequestBody; +import com.wechat.pay.java.core.http.HttpRequest; +import com.wechat.pay.java.core.http.JsonRequestBody; +import com.wechat.pay.java.core.http.OriginalResponse; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; @@ -25,17 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.wechat.pay.java.core.auth.Credential; -import com.wechat.pay.java.core.auth.Validator; -import com.wechat.pay.java.core.exception.HttpException; -import com.wechat.pay.java.core.exception.MalformedMessageException; -import com.wechat.pay.java.core.exception.ServiceException; -import com.wechat.pay.java.core.http.AbstractHttpClient; -import com.wechat.pay.java.core.http.FileRequestBody; -import com.wechat.pay.java.core.http.HttpRequest; -import com.wechat.pay.java.core.http.JsonRequestBody; -import com.wechat.pay.java.core.http.OriginalResponse; - public class ApacheHttpClientAdapter extends AbstractHttpClient { private static final Logger logger = LoggerFactory.getLogger(ApacheHttpClientAdapter.class); @@ -44,8 +42,8 @@ public class ApacheHttpClientAdapter extends AbstractHttpClient { private final CloseableHttpClient apacheHttpClient; - public ApacheHttpClientAdapter(Credential credential, Validator validator, - CloseableHttpClient client) { + public ApacheHttpClientAdapter( + Credential credential, Validator validator, CloseableHttpClient client) { super(credential, validator); this.apacheHttpClient = requireNonNull(client); } @@ -58,8 +56,8 @@ protected String getHttpClientInfo() { @Override public OriginalResponse innerExecute(HttpRequest wechatPayRequest) { try { - CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute( - buildApacheHttpRequest(wechatPayRequest)); + CloseableHttpResponse apacheHttpResponse = + apacheHttpClient.execute(buildApacheHttpRequest(wechatPayRequest)); return assembleOriginalResponse(wechatPayRequest, apacheHttpResponse); } catch (IOException e) { throw new HttpException(wechatPayRequest, e); @@ -72,27 +70,28 @@ private org.apache.http.client.methods.HttpUriRequest buildApacheHttpRequest( org.apache.http.client.methods.HttpUriRequest apacheHttpRequest; switch (wechatPayRequest.getHttpMethod().name()) { - case "GET": - apacheHttpRequest = new HttpGet(url); - break; - case "POST": - apacheHttpRequest = new HttpPost(url); - ((HttpPost) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); - break; - case "PUT": - apacheHttpRequest = new HttpPut(url); - ((HttpPut) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); - break; - case "PATCH": - apacheHttpRequest = new HttpPatch(url); - ((HttpPatch) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); - break; - case "DELETE": - apacheHttpRequest = new HttpDelete(url); - break; - default: - throw new IllegalArgumentException( - "Unsupported HTTP method: " + wechatPayRequest.getHttpMethod().name()); + case "GET": + apacheHttpRequest = new HttpGet(url); + break; + case "POST": + apacheHttpRequest = new HttpPost(url); + ((HttpPost) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); + break; + case "PUT": + apacheHttpRequest = new HttpPut(url); + ((HttpPut) apacheHttpRequest).setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); + break; + case "PATCH": + apacheHttpRequest = new HttpPatch(url); + ((HttpPatch) apacheHttpRequest) + .setEntity(buildApacheHttpEntity(wechatPayRequest.getBody())); + break; + case "DELETE": + apacheHttpRequest = new HttpDelete(url); + break; + default: + throw new IllegalArgumentException( + "Unsupported HTTP method: " + wechatPayRequest.getHttpMethod().name()); } Map headers = wechatPayRequest.getHeaders().getHeaders(); headers.forEach(apacheHttpRequest::addHeader); @@ -116,20 +115,23 @@ private HttpEntity buildApacheHttpEntity( MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.RFC6532); entityBuilder.addTextBody(META_NAME, fileRequestBody.getMeta(), APPLICATION_JSON); - entityBuilder.addBinaryBody(FILE_NAME, fileRequestBody.getFile(), - ContentType.create(fileRequestBody.getContentType()), fileRequestBody.getFileName()); + entityBuilder.addBinaryBody( + FILE_NAME, + fileRequestBody.getFile(), + ContentType.create(fileRequestBody.getContentType()), + fileRequestBody.getFileName()); return entityBuilder.build(); } logger.error( - "When an http request is sent and the apache request body is constructed, the requestBody" - + " parameter" + "When an http request is sent and the apache request body is constructed, the requestBody" + + " parameter" + " type cannot be found,requestBody class name[{}]", wechatPayRequestBody.getClass().getName()); return null; } - private OriginalResponse assembleOriginalResponse(HttpRequest wechatPayRequest, - CloseableHttpResponse apacheHttpResponse) throws IOException { + private OriginalResponse assembleOriginalResponse( + HttpRequest wechatPayRequest, CloseableHttpResponse apacheHttpResponse) throws IOException { Map responseHeaders = assembleResponseHeader(apacheHttpResponse); HttpEntity entity = apacheHttpResponse.getEntity(); try { @@ -161,11 +163,11 @@ private Map assembleResponseHeader(CloseableHttpResponse apacheH @Override protected InputStream innerDownload(HttpRequest httpRequest) { try { - CloseableHttpResponse apacheHttpResponse = apacheHttpClient.execute( - buildApacheHttpRequest(httpRequest)); + CloseableHttpResponse apacheHttpResponse = + apacheHttpClient.execute(buildApacheHttpRequest(httpRequest)); if (isInvalidHttpCode(apacheHttpResponse.getStatusLine().getStatusCode())) { - throw new ServiceException(httpRequest, apacheHttpResponse.getStatusLine().getStatusCode(), - ""); + throw new ServiceException( + httpRequest, apacheHttpResponse.getStatusLine().getStatusCode(), ""); } InputStream responseBodyStream = null; if (apacheHttpResponse.getEntity() != null) { diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java index d0fe7cff..f201f6fb 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java @@ -1,8 +1,22 @@ package com.wechat.pay.java.core.http; +import static com.wechat.pay.java.core.http.Constant.AUTHORIZATION; +import static com.wechat.pay.java.core.http.Constant.OS; +import static com.wechat.pay.java.core.http.Constant.USER_AGENT_FORMAT; +import static com.wechat.pay.java.core.http.Constant.VERSION; +import static com.wechat.pay.java.core.model.TestConfig.MERCHANT_ID; +import static com.wechat.pay.java.core.model.TestConfig.RESOURCES_DIR; + +import com.wechat.pay.java.core.auth.Credential; +import com.wechat.pay.java.core.auth.Validator; +import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; +import com.wechat.pay.java.core.model.TestServiceResponse; +import com.wechat.pay.java.core.util.IOUtil; import java.io.IOException; +import java.io.InputStream; import java.net.URI; - +import java.nio.file.Files; +import java.nio.file.Paths; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; @@ -13,34 +27,17 @@ import org.apache.http.ProtocolVersion; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicStatusLine; import org.apache.http.protocol.HttpContext; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.wechat.pay.java.core.auth.Credential; -import com.wechat.pay.java.core.auth.Validator; -import static com.wechat.pay.java.core.http.Constant.AUTHORIZATION; -import static com.wechat.pay.java.core.http.Constant.OS; -import static com.wechat.pay.java.core.http.Constant.USER_AGENT_FORMAT; -import static com.wechat.pay.java.core.http.Constant.VERSION; -import com.wechat.pay.java.core.http.okhttp.OkHttpClientAdapter; -import static com.wechat.pay.java.core.model.TestConfig.MERCHANT_ID; -import static com.wechat.pay.java.core.model.TestConfig.RESOURCES_DIR; -import com.wechat.pay.java.core.model.TestServiceResponse; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.io.InputStream; -import com.wechat.pay.java.core.util.IOUtil; - - public class ApacheHttpClientAdapterTest { private static final String APACHE_HTTP_CLIENT_MOCK_DATA_DIR = RESOURCES_DIR + "/http"; @@ -119,9 +116,11 @@ public String getSerialNumber() { executeSendGetCredential.getClass().getSimpleName(), executeSendGetRequestValidator.getClass().getSimpleName(), "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { + HttpRequestInterceptor requestInterceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { String executeSendGetMethod = request.getRequestLine().getMethod(); Assert.assertEquals(executeSendGetMethod, HttpMethod.GET.name()); String host = context.getAttribute("http.target_host").toString(); @@ -131,36 +130,43 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) th Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); Assert.assertEquals(FAKE_AUTHORIZATION, getHeaderValue(headers, AUTHORIZATION)); Assert.assertEquals( - executeSendGetCredential.getAuthorization(URI.create(URL), executeSendGetMethod, ""), + executeSendGetCredential.getAuthorization( + URI.create(URL), executeSendGetMethod, ""), getHeaderValue(headers, AUTHORIZATION)); - } + } - private String getHeaderValue(Header[] headers, String name) { + private String getHeaderValue(Header[] headers, String name) { for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } return null; - } - }; + } + }; - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); + response.setHeaders(new Header[] {header}); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = HttpStatus.SC_OK; String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); response.setStatusLine(statusLine); response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } - }; + } + }; CloseableHttpClient httpclient = - HttpClients.custom().addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build(); + HttpClients.custom() + .addInterceptorFirst(requestInterceptor) + .addInterceptorFirst(responseInterceptor) + .build(); HttpClient executeSendGetHttpClient = new ApacheHttpClientBuilder() .credential(executeSendGetCredential) @@ -191,1347 +197,1415 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) Assert.assertTrue(executeSendGetResponse.getBody() instanceof JsonResponseBody); Assert.assertEquals( RESPONSE_JSON, ((JsonResponseBody) executeSendGetResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendGetResponse.getServiceResponse().getRequestId()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendGetResponse.getServiceResponse().getRequestId()); } - @Test - public void testExecuteSendPostReqWithJsonBody() throws IOException { - Credential executeSendPostCredential = new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + @Test + public void testExecuteSendPostReqWithJsonBody() throws IOException { + Credential executeSendPostCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + @Override + public String getMerchantId() { + return MERCHANT_ID; + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.POST.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.POST.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } }; - Validator executeSendPostValidator = new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals(RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } + Validator executeSendPostValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } - @Override - public String getSerialNumber() { - return ""; - } + @Override + public String getSerialNumber() { + return ""; + } }; - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - executeSendPostCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - HttpEntity entity = new StringEntity( + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPostCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = + new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); - Assert.assertEquals(entity.getContentType().getValue(), reqEntity.getContentType().getValue()); - Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); - } + Assert.assertEquals( + entity.getContentType().getValue(), reqEntity.getContentType().getValue()); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } }; - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient executeSendPostHttpClient = new ApacheHttpClientBuilder() + HttpClient executeSendPostHttpClient = + new ApacheHttpClientBuilder() .credential(executeSendPostCredential) .validator(executeSendPostValidator) .apacheHttpClient(httpClient) .build(); + HttpRequest executeSendPostHttpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.POST) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); - HttpRequest executeSendPostHttpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.POST) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - - - HttpResponse executeSendPostResponse = + HttpResponse executeSendPostResponse = executeSendPostHttpClient.execute(executeSendPostHttpRequest, TestServiceResponse.class); - Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPostResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPostResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals(1, executeSendPostResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, executeSendPostResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPostResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPostResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPostResponse.getServiceResponse().getRequestId()); - } - - @Test - public void testExecuteSendPostReqWithFileBody() throws IOException { - String imageName = "test_image.jpg"; - String imagePath = APACHE_HTTP_CLIENT_MOCK_DATA_DIR + "/" + imageName; - InputStream inputStream = Files.newInputStream(Paths.get(imagePath)); - FileRequestBody requestBody = + Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPostResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPostResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendPostResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPostResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPostResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPostResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPostResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testExecuteSendPostReqWithFileBody() throws IOException { + String imageName = "test_image.jpg"; + String imagePath = APACHE_HTTP_CLIENT_MOCK_DATA_DIR + "/" + imageName; + InputStream inputStream = Files.newInputStream(Paths.get(imagePath)); + FileRequestBody requestBody = new FileRequestBody.Builder() .meta("meta") .fileName(imageName) .file(IOUtil.toByteArray(inputStream)) .build(); - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.RFC6532); - builder.addTextBody("meta", "meta"); - builder.addBinaryBody("file", requestBody.getFile(), ContentType.create(requestBody.getContentType()), imageName); - HttpEntity multipartEntity = builder.build(); - Credential executeSendPostWithFileCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.RFC6532); + builder.addTextBody("meta", "meta"); + builder.addBinaryBody( + "file", requestBody.getFile(), ContentType.create(requestBody.getContentType()), imageName); + HttpEntity multipartEntity = builder.build(); + Credential executeSendPostWithFileCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + @Override + public String getMerchantId() { + return MERCHANT_ID; + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.POST.name(), httpMethod); - System.out.println("signBody=" + signBody); - Assert.assertEquals("meta", signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator executeSendPostWithFileValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendPostWithFileCredential.getClass().getSimpleName(), - executeSendPostWithFileValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - executeSendPostWithFileCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - "meta"), - getHeaderValue(headers, AUTHORIZATION)); - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - // apache multipart entity content length 每次创建不一样,不做校验 - // Assert.assertEquals(multipartEntity.getContentLength(), reqEntity.getContentLength()); - } + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.POST.name(), httpMethod); + System.out.println("signBody=" + signBody); + Assert.assertEquals("meta", signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendPostWithFileValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; - } + @Override + public String getSerialNumber() { + return ""; + } }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendPostWithFileCredential.getClass().getSimpleName(), + executeSendPostWithFileValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPostWithFileCredential.getAuthorization( + URI.create(URL), request.getRequestLine().getMethod(), "meta"), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + // apache multipart entity content length 每次创建不一样,不做校验 + // Assert.assertEquals(multipartEntity.getContentLength(), + // reqEntity.getContentLength()); + } - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - System.out.println("process response: " + response); - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + System.out.println("process response: " + response); + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient executeSendPostWithFileHttpClient = new ApacheHttpClientBuilder() + HttpClient executeSendPostWithFileHttpClient = + new ApacheHttpClientBuilder() .credential(executeSendPostWithFileCredential) .validator(executeSendPostWithFileValidator) .apacheHttpClient(httpClient) .build(); + HttpRequest executeSendPostHttpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.POST) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); - HttpRequest executeSendPostHttpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.POST) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - - HttpResponse executeSendPostWithFileResponse = - executeSendPostWithFileHttpClient.post( + HttpResponse executeSendPostWithFileResponse = + executeSendPostWithFileHttpClient.post( requestHeaders, URL, requestBody, TestServiceResponse.class); + Assert.assertEquals( + 4, executeSendPostWithFileResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPostWithFileResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPostWithFileResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals( + HttpMethod.POST, executeSendPostWithFileResponse.getRequest().getHttpMethod()); + Assert.assertEquals(requestBody, executeSendPostWithFileResponse.getRequest().getBody()); + Assert.assertEquals(URL, executeSendPostWithFileResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPostWithFileResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, + executeSendPostWithFileResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPostWithFileResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPostWithFileResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPostWithFileResponse.getServiceResponse().getRequestId()); + } - Assert.assertEquals( - 4, executeSendPostWithFileResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPostWithFileResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPostWithFileResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.POST, executeSendPostWithFileResponse.getRequest().getHttpMethod()); - Assert.assertEquals(requestBody, executeSendPostWithFileResponse.getRequest().getBody()); - Assert.assertEquals(URL, executeSendPostWithFileResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPostWithFileResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPostWithFileResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPostWithFileResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPostWithFileResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPostWithFileResponse.getServiceResponse().getRequestId()); - } - - @Test - public void testExecuteSendPutRequest() throws IOException { - Credential executeSendPutCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } - - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + @Test + public void testExecuteSendPutRequest() throws IOException { + Credential executeSendPutCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.PUT.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator executeSendPutValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendPutCredential.getClass().getSimpleName(), - executeSendPutValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.PUT.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - executeSendPutCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - HttpEntity entity = new StringEntity( - JSON_REQUEST_BODY.getBody(), - ContentType.create(JSON_REQUEST_BODY.getContentType())); - Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); - } + @Override + public String getMerchantId() { + return MERCHANT_ID; + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; - } + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PUT.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } }; + Validator executeSendPutValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + @Override + public String getSerialNumber() { + return ""; + } }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendPutCredential.getClass().getSimpleName(), + executeSendPutValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PUT.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPutCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); - - HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = + new StringEntity( + JSON_REQUEST_BODY.getBody(), + ContentType.create(JSON_REQUEST_BODY.getContentType())); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } + + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } + } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } + }; + + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); + + HttpClient executeSendPutHttpClient = + new ApacheHttpClientBuilder() .credential(executeSendPutCredential) .validator(executeSendPutValidator) .apacheHttpClient(httpClient) .build(); + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.PUT) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); - HttpRequest httpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.PUT) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - - HttpResponse executeSendPutResponse = - executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - - Assert.assertEquals( - 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - - @Test - public void testExecuteSendPatchRequest() throws IOException { - Credential executeSendPatchCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.PATCH.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator executeSendPatchValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendPatchCredential.getClass().getSimpleName(), - executeSendPatchValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.PATCH.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - executeSendPatchCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - HttpEntity entity = new StringEntity( + @Test + public void testExecuteSendPatchRequest() throws IOException { + Credential executeSendPatchCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PATCH.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendPatchValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendPatchCredential.getClass().getSimpleName(), + executeSendPatchValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PATCH.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendPatchCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = + new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); - Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); - } + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } }; - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() + HttpClient executeSendPutHttpClient = + new ApacheHttpClientBuilder() .credential(executeSendPatchCredential) .validator(executeSendPatchValidator) .apacheHttpClient(httpClient) .build(); + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.PATCH) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); - HttpRequest httpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.PATCH) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - - HttpResponse executeSendPutResponse = - executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - - Assert.assertEquals( - 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.PATCH, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - - @Test - public void testExecuteSendDeleteRequest() throws IOException { - Credential executeSendDeleteCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.PATCH, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator executeSendDeleteValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendDeleteCredential.getClass().getSimpleName(), - executeSendDeleteValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.DELETE.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - executeSendDeleteCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - } + @Test + public void testExecuteSendDeleteRequest() throws IOException { + Credential executeSendDeleteCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; - } + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendDeleteValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendDeleteCredential.getClass().getSimpleName(), + executeSendDeleteValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.DELETE.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendDeleteCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + } - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() + HttpClient executeSendPutHttpClient = + new ApacheHttpClientBuilder() .credential(executeSendDeleteCredential) .validator(executeSendDeleteValidator) .apacheHttpClient(httpClient) .build(); + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.DELETE) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); - HttpRequest httpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.DELETE) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - - HttpResponse executeSendPutResponse = - executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - - Assert.assertEquals( - 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - - - @Test - public void testGet() { - Credential getCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.GET.name(), httpMethod); - Assert.assertEquals("", signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator getHttpValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - getCredential.getClass().getSimpleName(), - getHttpValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - String getMethod = request.getRequestLine().getMethod(); - Assert.assertEquals(getMethod, HttpMethod.GET.name()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals(FAKE_AUTHORIZATION, getHeaderValue(headers, AUTHORIZATION)); - Assert.assertEquals( - getCredential.getAuthorization(URI.create(URL), getMethod, ""), - getHeaderValue(headers, AUTHORIZATION)); - } + @Test + public void testGet() { + Credential getCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; - } + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.GET.name(), httpMethod); + Assert.assertEquals("", signBody); + return FAKE_AUTHORIZATION; + } }; + Validator getHttpValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + @Override + public String getSerialNumber() { + return ""; + } }; - CloseableHttpClient httpclient = - HttpClients.custom().addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build(); - - HttpClient getHttpClient = - new ApacheHttpClientBuilder() - .credential(getCredential) - .validator(getHttpValidator) - .apacheHttpClient(httpclient) - .build(); - - com.wechat.pay.java.core.http.HttpResponse executeSendGetResponse = - getHttpClient.get(requestHeaders, URL, TestServiceResponse.class); - - Assert.assertEquals(4, executeSendGetResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendGetResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendGetResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals(1, executeSendGetResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, executeSendGetResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendGetResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendGetResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendGetResponse.getServiceResponse().getRequestId()); - } - - @Test - public void testPost() throws IOException { - Credential postCredential = new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + getCredential.getClass().getSimpleName(), + getHttpValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor requestInterceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + String getMethod = request.getRequestLine().getMethod(); + Assert.assertEquals(getMethod, HttpMethod.GET.name()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals(FAKE_AUTHORIZATION, getHeaderValue(headers, AUTHORIZATION)); + Assert.assertEquals( + getCredential.getAuthorization(URI.create(URL), getMethod, ""), + getHeaderValue(headers, AUTHORIZATION)); + } - @Override - public String getMerchantId() { - return MERCHANT_ID; + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } + }; - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.POST.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - Validator postValidator = new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals(RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } + CloseableHttpClient httpclient = + HttpClients.custom() + .addInterceptorFirst(requestInterceptor) + .addInterceptorFirst(responseInterceptor) + .build(); - @Override - public String getSerialNumber() { - return ""; - } + HttpClient getHttpClient = + new ApacheHttpClientBuilder() + .credential(getCredential) + .validator(getHttpValidator) + .apacheHttpClient(httpclient) + .build(); + + com.wechat.pay.java.core.http.HttpResponse executeSendGetResponse = + getHttpClient.get(requestHeaders, URL, TestServiceResponse.class); + + Assert.assertEquals(4, executeSendGetResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendGetResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendGetResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendGetResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendGetResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendGetResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendGetResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendGetResponse.getServiceResponse().getRequestId()); + } + + @Test + public void testPost() throws IOException { + Credential postCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.POST.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator postValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } }; - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - postCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - HttpEntity entity = new StringEntity( + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.POST.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + postCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = + new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); - Assert.assertEquals(entity.getContentType().getValue(), reqEntity.getContentType().getValue()); - Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); - } + Assert.assertEquals( + entity.getContentType().getValue(), reqEntity.getContentType().getValue()); + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } }; - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient postHttpClient = new ApacheHttpClientBuilder() + HttpClient postHttpClient = + new ApacheHttpClientBuilder() .credential(postCredential) .validator(postValidator) .apacheHttpClient(httpClient) .build(); - HttpResponse executeSendPostResponse = - postHttpClient.post(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPostResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPostResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals(1, executeSendPostResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, executeSendPostResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPostResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPostResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPostResponse.getServiceResponse().getRequestId()); - } - - @Test - public void testPatch() throws IOException { - Credential patchCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + HttpResponse executeSendPostResponse = + postHttpClient.post(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); + Assert.assertEquals(4, executeSendPostResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPostResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPostResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(1, executeSendPostResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPostResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPostResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPostResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPostResponse.getServiceResponse().getRequestId()); + } - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + @Test + public void testPatch() throws IOException { + Credential patchCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.PATCH.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator patchValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - patchCredential.getClass().getSimpleName(), - patchValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.PATCH.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - patchCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - HttpEntity entity = new StringEntity( + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PATCH.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator patchValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + patchCredential.getClass().getSimpleName(), + patchValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PATCH.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + patchCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = + new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); - Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); - } + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } }; - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient patchHttpClient = new ApacheHttpClientBuilder() + HttpClient patchHttpClient = + new ApacheHttpClientBuilder() .credential(patchCredential) .validator(patchValidator) .apacheHttpClient(httpClient) .build(); - HttpResponse executeSendPutResponse = - patchHttpClient.patch(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - - - Assert.assertEquals( - 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.PATCH, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - - - @Test - public void testPut() throws IOException { - Credential putCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + HttpResponse executeSendPutResponse = + patchHttpClient.patch(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.PATCH, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.PUT.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator putValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - putCredential.getClass().getSimpleName(), - putValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.PUT.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - putCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - - Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - HttpEntity entity = new StringEntity( + @Test + public void testPut() throws IOException { + Credential putCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } + + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.PUT.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator putValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } + }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + putCredential.getClass().getSimpleName(), + putValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.PUT.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + putCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + + Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; + HttpEntity reqEntity = entityRequest.getEntity(); + HttpEntity entity = + new StringEntity( JSON_REQUEST_BODY.getBody(), ContentType.create(JSON_REQUEST_BODY.getContentType())); - Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); - } + Assert.assertEquals(entity.getContentLength(), reqEntity.getContentLength()); + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } }; - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); - } + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient putHttpClient = new ApacheHttpClientBuilder() + HttpClient putHttpClient = + new ApacheHttpClientBuilder() .credential(putCredential) .validator(putValidator) .apacheHttpClient(httpClient) .build(); - HttpResponse executeSendPutResponse = - putHttpClient.put(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - - - Assert.assertEquals( - 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } - - - @Test - public void testDelete() throws IOException { - Credential executeSendDeleteCredential = - new Credential() { - @Override - public String getSchema() { - return "fake-schema"; - } + HttpResponse executeSendPutResponse = + putHttpClient.put(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - @Override - public String getMerchantId() { - return MERCHANT_ID; - } + Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } - @Override - public String getAuthorization(URI uri, String httpMethod, String signBody) { - Assert.assertEquals(URI.create(URL), uri); - Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); - return FAKE_AUTHORIZATION; - } - }; - Validator executeSendDeleteValidator = - new Validator() { - @Override - public boolean validate(HttpHeaders responseHeaders, String body) { - Assert.assertNotNull(responseHeaders); - Assert.assertEquals(1, responseHeaders.getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); - Assert.assertEquals(RESPONSE_JSON, body); - return true; - } - - @Override - public String getSerialNumber() { - return ""; - } - }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendDeleteCredential.getClass().getSimpleName(), - executeSendDeleteValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); - HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { - @Override - public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException { - Assert.assertEquals(HttpMethod.DELETE.name(), request.getRequestLine().getMethod()); - String host = context.getAttribute("http.target_host").toString(); - Assert.assertEquals(URL, host + request.getRequestLine().getUri()); - Header[] headers = request.getAllHeaders(); - Assert.assertEquals(4, headers.length); - Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); - Assert.assertEquals( - executeSendDeleteCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), - getHeaderValue(headers, AUTHORIZATION)); - } + @Test + public void testDelete() throws IOException { + Credential executeSendDeleteCredential = + new Credential() { + @Override + public String getSchema() { + return "fake-schema"; + } - private String getHeaderValue(Header[] headers, String name) { - for (Header header : headers) { - if (header.getName().equalsIgnoreCase(name)) { - return header.getValue(); - } - } - return null; - } + @Override + public String getMerchantId() { + return MERCHANT_ID; + } + + @Override + public String getAuthorization(URI uri, String httpMethod, String signBody) { + Assert.assertEquals(URI.create(URL), uri); + Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); + Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + return FAKE_AUTHORIZATION; + } + }; + Validator executeSendDeleteValidator = + new Validator() { + @Override + public boolean validate(HttpHeaders responseHeaders, String body) { + Assert.assertNotNull(responseHeaders); + Assert.assertEquals(1, responseHeaders.getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, responseHeaders.getHeader(RESPONSE_HEADER_KEY)); + Assert.assertEquals(RESPONSE_JSON, body); + return true; + } + + @Override + public String getSerialNumber() { + return ""; + } }; + String userAgent = + String.format( + USER_AGENT_FORMAT, + OkHttpClientAdapter.class.getPackage().getImplementationVersion(), + OS, + VERSION == null ? "Unknown" : VERSION, + executeSendDeleteCredential.getClass().getSimpleName(), + executeSendDeleteValidator.getClass().getSimpleName(), + "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = + new HttpRequestInterceptor() { + @Override + public void process(org.apache.http.HttpRequest request, HttpContext context) + throws HttpException, IOException { + Assert.assertEquals(HttpMethod.DELETE.name(), request.getRequestLine().getMethod()); + String host = context.getAttribute("http.target_host").toString(); + Assert.assertEquals(URL, host + request.getRequestLine().getUri()); + Header[] headers = request.getAllHeaders(); + Assert.assertEquals(4, headers.length); + Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); + Assert.assertEquals( + executeSendDeleteCredential.getAuthorization( + URI.create(URL), + request.getRequestLine().getMethod(), + JSON_REQUEST_BODY.getBody()), + getHeaderValue(headers, AUTHORIZATION)); + } - HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { - @Override - public void process(org.apache.http.HttpResponse response, HttpContext context) throws HttpException, IOException { - Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); - response.setHeaders(new Header[]{header}); - - ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - int statusCode = HttpStatus.SC_OK; - String reasonPhrase = "OK"; - BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); - response.setStatusLine(statusLine); - response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + private String getHeaderValue(Header[] headers, String name) { + for (Header header : headers) { + if (header.getName().equalsIgnoreCase(name)) { + return header.getValue(); + } } + return null; + } + }; + + HttpResponseInterceptor responseInterceptor = + new HttpResponseInterceptor() { + @Override + public void process(org.apache.http.HttpResponse response, HttpContext context) + throws HttpException, IOException { + Header header = new BasicHeader(RESPONSE_HEADER_KEY, RESPONSE_HEADER_VALUE); + response.setHeaders(new Header[] {header}); + + ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); + int statusCode = HttpStatus.SC_OK; + String reasonPhrase = "OK"; + BasicStatusLine statusLine = + new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); + response.setStatusLine(statusLine); + response.setEntity(new StringEntity(RESPONSE_JSON, ContentType.APPLICATION_JSON)); + } }; - CloseableHttpClient httpClient = HttpClients.custom(). - addInterceptorFirst(interceptor). - addInterceptorLast(responseInterceptor).build(); + CloseableHttpClient httpClient = + HttpClients.custom() + .addInterceptorFirst(interceptor) + .addInterceptorLast(responseInterceptor) + .build(); - HttpClient executeSendPutHttpClient = new ApacheHttpClientBuilder() + HttpClient executeSendPutHttpClient = + new ApacheHttpClientBuilder() .credential(executeSendDeleteCredential) .validator(executeSendDeleteValidator) .apacheHttpClient(httpClient) .build(); + HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.DELETE) + .url(URL) + .headers(requestHeaders) + .body(JSON_REQUEST_BODY) + .build(); - HttpRequest httpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.DELETE) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - - HttpResponse executeSendPutResponse = - executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); - - - Assert.assertEquals( - 4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); - Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); - Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals( - HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, - executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals(RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); - } + HttpResponse executeSendPutResponse = + executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); + Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals( + REQUEST_HEADER_VALUE, + executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + Assert.assertEquals( + FAKE_AUTHORIZATION, + executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + Assert.assertEquals( + RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals( + RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); + Assert.assertEquals( + RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + } } diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java index b86462a9..0a2175c9 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilderTest.java @@ -1,23 +1,18 @@ package com.wechat.pay.java.core.http; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.auth.Credential; import com.wechat.pay.java.core.auth.Validator; import com.wechat.pay.java.core.cipher.PrivacyDecryptor; import com.wechat.pay.java.core.cipher.PrivacyEncryptor; import com.wechat.pay.java.core.cipher.Signer; -import okhttp3.OkHttpClient; +import java.net.URI; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.jupiter.api.Test; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.Proxy.Type; -import java.net.URI; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - class ApacheHttpClientBuilderTest { Credential credential = @@ -93,8 +88,7 @@ public Signer createSigner() { return null; } }; - HttpClient httpClient = - new ApacheHttpClientBuilder().config(config).build(); + HttpClient httpClient = new ApacheHttpClientBuilder().config(config).build(); assertNotNull(httpClient); } } From 0845ee161be7f8d5c916a790194cd703fcf1630b Mon Sep 17 00:00:00 2001 From: masutangu Date: Fri, 29 Nov 2024 14:39:33 +0800 Subject: [PATCH 06/10] fix issue --- .../core/http/ApacheHttpClientBuilder.java | 3 - .../http/ApacheHttpClientAdapterTest.java | 128 ++---------------- 2 files changed, 15 insertions(+), 116 deletions(-) diff --git a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java index 50782093..221526eb 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java @@ -6,7 +6,6 @@ import com.wechat.pay.java.core.auth.Credential; import com.wechat.pay.java.core.auth.Validator; import com.wechat.pay.java.core.http.apache.ApacheHttpClientAdapter; -import com.wechat.pay.java.core.http.okhttp.OkHttpMultiDomainInterceptor; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; @@ -18,8 +17,6 @@ public class ApacheHttpClientBuilder implements AbstractHttpClientBuilder String getSerialNumber() { } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendGetCredential.getClass().getSimpleName(), - executeSendGetRequestValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { @Override @@ -395,15 +382,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendPostWithFileCredential.getClass().getSimpleName(), - executeSendPostWithFileValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -421,11 +400,6 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) getHeaderValue(headers, AUTHORIZATION)); Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - HttpEntity reqEntity = entityRequest.getEntity(); - // apache multipart entity content length 每次创建不一样,不做校验 - // Assert.assertEquals(multipartEntity.getContentLength(), - // reqEntity.getContentLength()); } private String getHeaderValue(Header[] headers, String name) { @@ -470,14 +444,6 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) .apacheHttpClient(httpClient) .build(); - HttpRequest executeSendPostHttpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.POST) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - HttpResponse executeSendPostWithFileResponse = executeSendPostWithFileHttpClient.post( requestHeaders, URL, requestBody, TestServiceResponse.class); @@ -506,7 +472,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testExecuteSendPutRequest() throws IOException { + public void testExecuteSendPutRequest() { Credential executeSendPutCredential = new Credential() { @Override @@ -544,15 +510,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendPutCredential.getClass().getSimpleName(), - executeSendPutValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -653,7 +611,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testExecuteSendPatchRequest() throws IOException { + public void testExecuteSendPatchRequest() { Credential executeSendPatchCredential = new Credential() { @Override @@ -691,15 +649,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendPatchCredential.getClass().getSimpleName(), - executeSendPatchValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -838,15 +788,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendDeleteCredential.getClass().getSimpleName(), - executeSendDeleteValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -976,15 +918,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - getCredential.getClass().getSimpleName(), - getHttpValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { @Override @@ -1194,7 +1128,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testPatch() throws IOException { + public void testPatch() { Credential patchCredential = new Credential() { @Override @@ -1232,15 +1166,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - patchCredential.getClass().getSimpleName(), - patchValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -1333,7 +1259,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testPut() throws IOException { + public void testPut() { Credential putCredential = new Credential() { @Override @@ -1371,15 +1297,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - putCredential.getClass().getSimpleName(), - putValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -1472,7 +1390,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testDelete() throws IOException { + public void testDelete() { Credential executeSendDeleteCredential = new Credential() { @Override @@ -1510,15 +1428,7 @@ public String getSerialNumber() { return ""; } }; - String userAgent = - String.format( - USER_AGENT_FORMAT, - OkHttpClientAdapter.class.getPackage().getImplementationVersion(), - OS, - VERSION == null ? "Unknown" : VERSION, - executeSendDeleteCredential.getClass().getSimpleName(), - executeSendDeleteValidator.getClass().getSimpleName(), - "apachehttp/" + getClass().getPackage().getImplementationVersion()); + HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override @@ -1572,23 +1482,15 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) .addInterceptorLast(responseInterceptor) .build(); - HttpClient executeSendPutHttpClient = + HttpClient deleteHttpClient = new ApacheHttpClientBuilder() .credential(executeSendDeleteCredential) .validator(executeSendDeleteValidator) .apacheHttpClient(httpClient) .build(); - HttpRequest httpRequest = - new HttpRequest.Builder() - .httpMethod(HttpMethod.DELETE) - .url(URL) - .headers(requestHeaders) - .body(JSON_REQUEST_BODY) - .build(); - HttpResponse executeSendPutResponse = - executeSendPutHttpClient.execute(httpRequest, TestServiceResponse.class); + deleteHttpClient.delete(requestHeaders, URL, TestServiceResponse.class); Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( From 8d0ffed21b56fc1b80aa6059542028c468dc8f11 Mon Sep 17 00:00:00 2001 From: masutangu Date: Fri, 29 Nov 2024 16:20:05 +0800 Subject: [PATCH 07/10] fix issue --- .../http/ApacheHttpClientAdapterTest.java | 74 ++++++++----------- 1 file changed, 31 insertions(+), 43 deletions(-) diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java index d2772887..8e19f3da 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java @@ -767,7 +767,7 @@ public String getMerchantId() { public String getAuthorization(URI uri, String httpMethod, String signBody) { Assert.assertEquals(URI.create(URL), uri); Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + Assert.assertEquals("", signBody); return FAKE_AUTHORIZATION; } }; @@ -802,9 +802,7 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); Assert.assertEquals( executeSendDeleteCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), + URI.create(URL), request.getRequestLine().getMethod(), ""), getHeaderValue(headers, AUTHORIZATION)); } @@ -854,7 +852,6 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) .httpMethod(HttpMethod.DELETE) .url(URL) .headers(requestHeaders) - .body(JSON_REQUEST_BODY) .build(); HttpResponse executeSendPutResponse = @@ -1367,31 +1364,27 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) .apacheHttpClient(httpClient) .build(); - HttpResponse executeSendPutResponse = + HttpResponse putResponse = putHttpClient.put(requestHeaders, URL, JSON_REQUEST_BODY, TestServiceResponse.class); - Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals(4, putResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( - REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + REQUEST_HEADER_VALUE, putResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals(HttpMethod.PUT, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); - Assert.assertEquals( - RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); + FAKE_AUTHORIZATION, putResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.PUT, putResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, putResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, putResponse.getHeaders().getHeaders().size()); Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals( - RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + RESPONSE_HEADER_VALUE, putResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(putResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals(RESPONSE_JSON, ((JsonResponseBody) putResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, putResponse.getServiceResponse().getRequestId()); } @Test public void testDelete() { - Credential executeSendDeleteCredential = + Credential deleteCredential = new Credential() { @Override public String getSchema() { @@ -1407,11 +1400,11 @@ public String getMerchantId() { public String getAuthorization(URI uri, String httpMethod, String signBody) { Assert.assertEquals(URI.create(URL), uri); Assert.assertEquals(HttpMethod.DELETE.name(), httpMethod); - Assert.assertEquals(JSON_REQUEST_BODY.getBody(), signBody); + Assert.assertEquals("", signBody); return FAKE_AUTHORIZATION; } }; - Validator executeSendDeleteValidator = + Validator deleteValidator = new Validator() { @Override public boolean validate(HttpHeaders responseHeaders, String body) { @@ -1441,10 +1434,8 @@ public void process(org.apache.http.HttpRequest request, HttpContext context) Assert.assertEquals(4, headers.length); Assert.assertEquals(REQUEST_HEADER_VALUE, getHeaderValue(headers, REQUEST_HEADER_KEY)); Assert.assertEquals( - executeSendDeleteCredential.getAuthorization( - URI.create(URL), - request.getRequestLine().getMethod(), - JSON_REQUEST_BODY.getBody()), + deleteCredential.getAuthorization( + URI.create(URL), request.getRequestLine().getMethod(), ""), getHeaderValue(headers, AUTHORIZATION)); } @@ -1484,30 +1475,27 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) HttpClient deleteHttpClient = new ApacheHttpClientBuilder() - .credential(executeSendDeleteCredential) - .validator(executeSendDeleteValidator) + .credential(deleteCredential) + .validator(deleteValidator) .apacheHttpClient(httpClient) .build(); - HttpResponse executeSendPutResponse = + HttpResponse deleteResponse = deleteHttpClient.delete(requestHeaders, URL, TestServiceResponse.class); - Assert.assertEquals(4, executeSendPutResponse.getRequest().getHeaders().getHeaders().size()); + Assert.assertEquals(4, deleteResponse.getRequest().getHeaders().getHeaders().size()); Assert.assertEquals( REQUEST_HEADER_VALUE, - executeSendPutResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); + deleteResponse.getRequest().getHeaders().getHeader(REQUEST_HEADER_KEY)); Assert.assertEquals( - FAKE_AUTHORIZATION, - executeSendPutResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); - Assert.assertEquals(HttpMethod.DELETE, executeSendPutResponse.getRequest().getHttpMethod()); - Assert.assertEquals(URL, executeSendPutResponse.getRequest().getUrl().toString()); - Assert.assertEquals(1, executeSendPutResponse.getHeaders().getHeaders().size()); + FAKE_AUTHORIZATION, deleteResponse.getRequest().getHeaders().getHeader(AUTHORIZATION)); + Assert.assertEquals(HttpMethod.DELETE, deleteResponse.getRequest().getHttpMethod()); + Assert.assertEquals(URL, deleteResponse.getRequest().getUrl().toString()); + Assert.assertEquals(1, deleteResponse.getHeaders().getHeaders().size()); Assert.assertEquals( - RESPONSE_HEADER_VALUE, executeSendPutResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); - Assert.assertTrue(executeSendPutResponse.getBody() instanceof JsonResponseBody); - Assert.assertEquals( - RESPONSE_JSON, ((JsonResponseBody) executeSendPutResponse.getBody()).getBody()); - Assert.assertEquals( - RESPONSE_JSON_VALUE, executeSendPutResponse.getServiceResponse().getRequestId()); + RESPONSE_HEADER_VALUE, deleteResponse.getHeaders().getHeader(RESPONSE_HEADER_KEY)); + Assert.assertTrue(deleteResponse.getBody() instanceof JsonResponseBody); + Assert.assertEquals(RESPONSE_JSON, ((JsonResponseBody) deleteResponse.getBody()).getBody()); + Assert.assertEquals(RESPONSE_JSON_VALUE, deleteResponse.getServiceResponse().getRequestId()); } } From 7af8525bfd9c435706abdd176fb317e35bd2848d Mon Sep 17 00:00:00 2001 From: masutangu Date: Fri, 29 Nov 2024 16:33:04 +0800 Subject: [PATCH 08/10] fix issue --- .../pay/java/core/http/ApacheHttpClientAdapterTest.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java index 8e19f3da..c331bf44 100644 --- a/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java +++ b/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java @@ -189,7 +189,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testExecuteSendPostReqWithJsonBody() throws IOException { + public void testExecuteSendPostReqWithJsonBody() { Credential executeSendPostCredential = new Credential() { @Override @@ -343,7 +343,6 @@ public void testExecuteSendPostReqWithFileBody() throws IOException { builder.addTextBody("meta", "meta"); builder.addBinaryBody( "file", requestBody.getFile(), ContentType.create(requestBody.getContentType()), imageName); - HttpEntity multipartEntity = builder.build(); Credential executeSendPostWithFileCredential = new Credential() { @Override @@ -750,7 +749,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testExecuteSendDeleteRequest() throws IOException { + public void testExecuteSendDeleteRequest() { Credential executeSendDeleteCredential = new Credential() { @Override @@ -995,7 +994,7 @@ public void process(org.apache.http.HttpResponse response, HttpContext context) } @Test - public void testPost() throws IOException { + public void testPost() { Credential postCredential = new Credential() { @Override From 13b002fbd5c1865bca6980c9681bc3846f02a159 Mon Sep 17 00:00:00 2001 From: masutangu Date: Mon, 9 Dec 2024 11:16:29 +0800 Subject: [PATCH 09/10] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/java/core/http/ApacheHttpClientBuilder.java | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java index 221526eb..261e47c0 100644 --- a/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java +++ b/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java @@ -46,7 +46,7 @@ public ApacheHttpClientBuilder newInstance() { * 设置凭据生成器 * * @param credential 凭据生成器 - * @return defaultHttpClientBuilder + * @return apacheHttpClientBuilder */ @Override public ApacheHttpClientBuilder credential(Credential credential) { @@ -58,7 +58,7 @@ public ApacheHttpClientBuilder credential(Credential credential) { * 设置验证器 * * @param validator 验证器 - * @return defaultHttpClientBuilder + * @return apacheHttpClientBuilder */ @Override public ApacheHttpClientBuilder validator(Validator validator) { @@ -67,10 +67,10 @@ public ApacheHttpClientBuilder validator(Validator validator) { } /** - * 设置 appacheHttpClient 若设置该client,则忽略其他参数 + * 设置 appacheHttpClient,若没有设置,则使用默认创建的 appacheHttpClient * * @param apacheHttpClient 用户自定义的apacheHttpClient - * @return defaultHttpClientBuilder + * @return apacheHttpClientBuilder */ public ApacheHttpClientBuilder apacheHttpClient(CloseableHttpClient apacheHttpClient) { this.customizeApacheHttpClient = apacheHttpClient; @@ -98,9 +98,6 @@ public AbstractHttpClient build() { customizeApacheHttpClient == null ? initDefaultApacheHttpClient() : customizeApacheHttpClient; - // 每次都会创建一个 httpclient 实例,和 okhttp 不同 - // You can customize a shared OkH(ttpClient instance with newBuilder(). This builds a client - // that shares the same connection po)ol, thread pools, and configuration. return new ApacheHttpClientAdapter(credential, validator, httpclient); } } From 2f287d7dd96c69a003ad8f94fdf803a9794081e6 Mon Sep 17 00:00:00 2001 From: masutangu Date: Fri, 13 Dec 2024 11:59:10 +0800 Subject: [PATCH 10/10] =?UTF-8?q?readme=20=E6=96=B0=E5=A2=9E=20apacheHttpC?= =?UTF-8?q?lient=20=E7=9B=B8=E5=85=B3=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/README.md b/README.md index a615c065..46ca9604 100644 --- a/README.md +++ b/README.md @@ -474,6 +474,54 @@ JsapiService service = new JsapiService.Builder().httpclient(httpClient).build() 我们提供基于 [腾讯 Kona 国密套件](https://github.com/Tencent/TencentKonaSMSuite) 的国密扩展。文档请参考 [shangmi/README.md](shangmi/README.md)。 +## 使用 ApacheHttpClient 发送 HTTP请求 + +SDK 支持使用 ApacheHttpClient 发送 HTTP 请求。建议使用 [ApacheHttpClientBuilder](https://github.com/wechatpay-apiv3/wechatpay-java/tree/main/core/src/main/java/com/wechat/pay/java/core/http/ApacheHttpClientBuilder.java) 创建 [ApacheHttpClientAdapter]https://github.com/wechatpay-apiv3/wechatpay-java/tree/main/core/src/main/java/com/wechat/pay/java/core/http/apache/ApacheHttpClientAdapter.java) 来发送 HTTP 请求,会自动生成签名和验证签名。 + +### 使用示例 + +发送请求步骤如下: + +1. 初始化 `ApacheHttpClientAdapter`,建议使用 `ApacheHttpClientBuilder` 构建 +2. 构建请求 `HttpRequest` +3. 调用 `httpClient.execute` 或者 `httpClient.get` 等方法来发送 HTTP 请求。`httpClient.execute` 支持发送 GET、PUT、POST、PATCH、DELETE 请求,也可以调用指定的 HTTP 方法发送请求。 + +[ApacheHttpClientAdapterTest](https://github.com/wechatpay-apiv3/wechatpay-java/blob/main/core/src/test/java/com/wechat/pay/java/core/http/ApacheHttpClientAdapterTest.java) 中演示了如何构造和发送 HTTP 请求。以下是简单的代码使用示例: + +```java +// 初始化商户配置 +Config config = +new RSAAutoCertificateConfig.Builder() +.merchantId(merchantId) // 商户号 +.privateKeyFromPath(privateKeyPath) // 商户API私钥路径 +.merchantSerialNumber(merchantSerialNumber) // 商户证书序列号 +.apiV3Key(apiV3Key) // 商户APIV3密钥 +.build(); + +// 方法一:使用默认创建的 ApacheHttpClient +HttpClient httpClient = new ApacheHttpClientBuilder().config(config).build(); +// 方法二:使用业务已有的 customApacheHttpClient +HttpClient httpClient = new ApacheHttpClientBuilder().config(config).apacheHttpClient(customApacheHttpClient).build(); + +// 构造 HttpRequest,以 GET 为例 +HttpRequest httpRequest = + new HttpRequest.Builder() + .httpMethod(HttpMethod.GET) + .url(requestPath) + .headers(headers) + .build(); + +// 发送请求 Response 为自定义的回包的类型 +HttpResponse httpResponse = httpClient.execute(httpRequest, ExampleResponse.class); +``` + +### 如何迁移 + +如果之前使用的是 [wechatpay-apache-httpclient](https://github.com/wechatpay-apiv3/wechatpay-apache-httpclient),想要迁移到使用 SDK,可以按照以下步骤: + +1. 修改初始化方式:可参考示例代码 +2. 修改收发包请求:定义回包类 XXXResponse,构造 HttpRequest,可参考示例代码 + ## 常见问题 ### 为什么收到应答中的证书序列号和发起请求的证书序列号不一致?