- HttpClientHelper
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class HttpClientHelper {
private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
private static HttpClientHelper instance = null;
private static Lock lock = new ReentrantLock();
private static CloseableHttpClient httpClient;
public HttpClientHelper() {
instance = this;
}
public static HttpClientHelper getHttpClient() {
if (instance == null) {
lock.lock();
try {
instance = new HttpClientHelper();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
return instance;
}
public void init() {
PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
pool.setMaxTotal(500);
pool.setDefaultMaxPerRoute(50);
httpClient = HttpClientBuilder.create().setConnectionManager(pool).build();
}
public byte[] executeAndReturnByte(HttpRequestBase request) throws Exception {
HttpEntity entity = null;
CloseableHttpResponse response = null;
byte[] base = new byte[0];
if (request == null) {
return base;
}
if (httpClient == null) {
init();
}
if (httpClient == null) {
logger.error("http获取异常");
return base;
}
response = httpClient.execute(request);
entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200) {
String encode = ("" + response.getFirstHeader("Content-Encoding")).toLowerCase();
if (encode.indexOf("gzip") > 0) {
entity = new GzipDecompressingEntity(entity);
}
base = EntityUtils.toByteArray(entity);
} else {
logger.error("" + response.getStatusLine().getStatusCode());
}
EntityUtils.consumeQuietly(entity);
response.close();
return base;
}
public String execute(HttpRequestBase request) throws Exception {
byte[] base = executeAndReturnByte(request);
if (base == null) {
return null;
}
return new String(base, StandardCharsets.UTF_8);
}
}
- 调用HttpUtil实现
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.message.BasicNameValuePair;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class HttpUtil {
private static String UTF8 = "UTF-8";
private static RequestConfig requestConfig;
public static boolean isRequestSuccessful(HttpResponse httpresponse) {
return httpresponse.getStatusLine().getStatusCode() == 200;
}
public static String get(String url) throws Exception {
HttpGet get = null;
get = new HttpGet(url);
return HttpClientHelper.getHttpClient().execute(get);
}
public static String get(Map<String, String> header, String url) throws Exception {
HttpGet get = null;
get = new HttpGet(url);
if (header != null) {
for (String key : header.keySet()) {
get.addHeader(key, header.get(key));
}
}
return HttpClientHelper.getHttpClient().execute(get);
}
public static String post(Map<String, String> header, Map<String, String> params, String url) throws Exception {
HttpPost post = null;
post = new HttpPost(url);
if (header != null) {
for (String key : header.keySet()) {
post.addHeader(key, header.get(key));
}
}
if (params != null) {
List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
post.setConfig(getRequestConfig());
for (String key : params.keySet()) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, UTF8);
post.setEntity(entity);
}
return HttpClientHelper.getHttpClient().execute(post);
}
public static String post(Map<String, String> header, String jsonObject, String url) throws Exception {
HttpPost post = null;
post = new HttpPost(url);
if (header != null) {
for (String key : header.keySet()) {
post.addHeader(key, header.get(key));
}
}
if (jsonObject.isEmpty()) {
throw new Exception("jsonObject不能为空!");
}
HttpEntity entity = new StringEntity(jsonObject, ContentType.APPLICATION_JSON.toString(), "UTF-8");
post.setEntity(entity);
return HttpClientHelper.getHttpClient().execute(post);
}
public static String post(MultipartFile file, Map<String, String> header, String url) throws Exception {
HttpPost post = new HttpPost(url);
if (MapUtils.isNotEmpty(header)) {
for (String key : header.keySet()) {
post.addHeader(key, header.get(key));
}
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());
HttpEntity entity = builder.build();
post.setEntity(entity);
return HttpClientHelper.getHttpClient().execute(post);
}
public static String post(String jsonObjectStr, String url) throws Exception {
HttpPost post = null;
post = new HttpPost(url);
if (jsonObjectStr.isEmpty()) {
throw new Exception("jsonObjectStr不能为空!");
}
HttpEntity entity = new StringEntity(jsonObjectStr, "UTF-8");
post.setEntity(entity);
return HttpClientHelper.getHttpClient().execute(post);
}
public static String post(Map<String, String> params, String url) throws Exception {
HttpPost post = null;
post = new HttpPost(url);
List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
post.setConfig(getRequestConfig());
for (String key : params.keySet()) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, UTF8);
post.setEntity(entity);
return HttpClientHelper.getHttpClient().execute(post);
}
public static RequestConfig getRequestConfig() {
if (requestConfig == null) {
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)
.setConnectTimeout(20000).setSocketTimeout(20000).build();
}
return requestConfig;
}
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client_IP");
}
if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.length() < 5) {
ip = "0.0.0.0";
}
return ip;
}
}