org.kaizen4j.common.httpclient.HttpClientProxy Maven / Gradle / Ivy
package org.kaizen4j.common.httpclient;
import com.google.common.base.Preconditions;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.kaizen4j.common.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
/**
* HTTP 客户端代理类
*/
public final class HttpClientProxy extends AbstractHttpClientProxy {
private static final Logger logger = LoggerFactory.getLogger(HttpClientProxy.class);
private CloseableHttpClient httpClient;
HttpClientProxy(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
protected HttpResult request(HttpRequestBase httpRequestBase, Map requestHeader) {
Preconditions.checkNotNull(httpRequestBase, "HttpRequestBase must be not null");
String method = httpRequestBase.getRequestLine().getMethod();
logger.info("Send {} request url: {}", method, httpRequestBase.getRequestLine().getUri());
if (!CollectionUtils.isEmpty(requestHeader)) {
requestHeader.forEach((name, value) -> httpRequestBase.setHeader(name, value));
logger.info("Send {} request header: {}", method, JsonUtils.getJson(requestHeader));
}
HttpResult httpResult = new HttpResult();
try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequestBase, HttpClientContext.create())) {
HttpEntity responseEntity = httpResponse.getEntity();
if (Objects.nonNull(responseEntity) && HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
httpResult.setBody(EntityUtils.toString(responseEntity));
}
httpResult.setStatus(httpResponse.getStatusLine().getStatusCode());
/* 释放资源 */
EntityUtils.consume(responseEntity);
} catch (IOException e) {
httpResult.setStatus(HTTP_INTERNAL_ERROR);
httpResult.setBody(e.getMessage());
logger.error("Send request [" + httpRequestBase.getRequestLine().getUri() + "] failed", e);
} finally {
/* 释放资源 */
httpRequestBase.releaseConnection();
}
return httpResult;
}
}