1、引入maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
2、封装http工具类
package cn.toroot.bj.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.routing.HttpRoute;
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.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
public class HttpUtil {
private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
private static CloseableHttpClient httpClient;
private static Charset UTF_8 = Charset.forName("UTF-8");
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
HttpHost localhost = new HttpHost("localhost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public static String post(String url, String content) {
logger.debug("{} - {}", url, content);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
if (content != null) {
HttpEntity httpEntity = new StringEntity(content, UTF_8);
httppost.setEntity(httpEntity);
}
return execute(httppost);
}
public static String postFile(String url, String localFile, Map<String,String> stringParts) {
logger.debug("{} - {}", url, localFile);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
MultipartEntityBuilder build = MultipartEntityBuilder.create();
build.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
build.setCharset(Charset.forName("utf-8"));
if(null != localFile && localFile.length() > 0){
FileBody fileBody = new FileBody(new File(localFile));
build.addPart("file",fileBody);
}
if(null != stringParts) {
for (Map.Entry<String, String> entry : stringParts.entrySet()) {
StringBody stringBody = new StringBody(entry.getValue(), ContentType.create("text/plain", UTF_8));
build.addPart(entry.getKey(), stringBody);
}
}
HttpEntity reqEntity = build.build();
httppost.setEntity(reqEntity);
return execute(httppost);
}
public static String postFile(String url, String localFile) {
return postFile(url,localFile,null);
}
public static String post4GzipResponse(String url, String content) {
logger.debug("{} - {}", url, content);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
httppost.addHeader("Accept-Encoding", "gzip");
if (content != null) {
HttpEntity httpEntity = new StringEntity(content, UTF_8);
httppost.setEntity(httpEntity);
}
return execute(httppost);
}
public static String postAsJson(String url, String content) {
logger.debug("{} - {}", url, content);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
HttpEntity httpEntity = new StringEntity(content, ContentType.APPLICATION_JSON);
httppost.setEntity(httpEntity);
return execute(httppost);
}
public static String get(String url) {
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
return execute(httpGet);
}
private static String execute(HttpRequestBase httpRequestBase) {
String result = null;
try {
HttpResponse response = httpClient.execute(httpRequestBase);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, UTF_8);
EntityUtils.consume(resEntity);
if (result.length() < 2000) {
logger.debug(result);
} else {
if (logger.isTraceEnabled()) {
logger.trace(result);
}
}
}
} catch (IOException e) {
logger.error("", e);
}
return result;
}
public static void main(String[] args) {
String res = HttpUtil.get("http://www.baidu.com");
System.out.println("res = " + res);
}
public static String sendPost(String url, String intface, Object param) {
return postAsJson(url + intface,JsonUtils.obj2json(param));
}
}