闲来无事,研究了会HttpAsyncClient,写了一个工具类,替代现有的http工具类
先是maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient-cache</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
</dependency>
再是工具类代码
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* http处理类
* 使用apache的HttpClient
* @author zhangle
*/
public class HttpUtil {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final ObjectMapper mapper = new ObjectMapper();
public static String get(String url) throws Exception {
return asyncRequest("get",url,null,null);
}
public static String get(String url, Map<String, String> params) throws Exception {
return asyncRequest("get",url,params,null);
}
public static String post(String url) throws Exception {
return asyncRequest("post",url,null,null);
}
public static String post(String url, Map<String, String> params) throws Exception {
return asyncRequest("post",url,params,null);
}
/**
* post json对象
* @param url
* @param jsonObj
* @return
* @throws Exception
*/
public static String postJson(String url, Object jsonObj) throws Exception {
RequestConfig requestConfig = createRequestConfig();
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
try {
httpclient.start();
HttpUriRequest request = createPostJsonRequest(url, jsonObj);
Future<HttpResponse> future = httpclient.execute(request, null);
HttpResponse response = future.get(3000,TimeUnit.MILLISECONDS);
return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
} finally {
httpclient.close();
}
}
public static <T> T postJson(String url, Object jsonObj,Class<T> clazz) throws Exception {
String res=postJson(url,jsonObj);
return mapper.readValue(res, clazz);
}
public static String asyncRequest(String method,String url, Map<String, String> params, Map<String, String> headers) throws Exception {
RequestConfig requestConfig = createRequestConfig();
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
try {
httpclient.start();
HttpUriRequest request = createHttpUriRequest(method, url, params, headers);
Future<HttpResponse> future = httpclient.execute(request, null);
HttpResponse response = future.get(3000,TimeUnit.MILLISECONDS);
return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
} finally {
httpclient.close();
}
}
public static String request(String method,String url, Map<String, String> params, Map<String, String> headers) throws Exception {
RequestConfig requestConfig = createRequestConfig();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
try {
HttpUriRequest request = createHttpUriRequest(method, url, params, headers);
CloseableHttpResponse response = httpclient.execute(request);
return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
} finally {
httpclient.close();
}
}
/**
* 上传文件
* @param url
* @param paramName
* @param file
* @return
* @throws Exception
*/
public static String upload(String url, String paramName, File file) throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(6000)
.setConnectionRequestTimeout(6000)
.build();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody(paramName,file);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
CloseableHttpResponse response = httpclient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
} finally {
httpclient.close();
}
}
private static HttpUriRequest createHttpUriRequest(String method, String url, Map<String, String> params, Map<String, String> headers) {
RequestBuilder builder = RequestBuilder.create(method.toUpperCase()).setUri(url);
builder.setCharset(Consts.UTF_8);
//builder.setConfig(requestConfig);
Optional.ofNullable(headers).ifPresent(map -> {
map.forEach((key, val) -> {
builder.addHeader(key, val);
});
});
Optional.ofNullable(params).ifPresent(map -> {
map.forEach((key, val) -> {
builder.addParameter(key, val);
});
});
return builder.build();
}
private static HttpUriRequest createPostJsonRequest(String url, Object jsonObj) throws JsonProcessingException {
RequestBuilder builder = RequestBuilder.post(url);
builder.setCharset(Consts.UTF_8);
//builder.setConfig(requestConfig);
String jsonStr=mapper.writeValueAsString(jsonObj);
StringEntity jsonEntity=new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
builder.setEntity(jsonEntity);
return builder.build();
}
private static RequestConfig createRequestConfig() {
return RequestConfig.custom()
.setSocketTimeout(3000)
.setConnectTimeout(3000)
.setConnectionRequestTimeout(3000)
.build();
}
public static void main(String[] args) throws Exception {
String content=HttpUtil.get("http://www.apache.org/");
System.out.println(content);
}
}
然后是运行main方法,测试发送http请求。
public static void main(String[] args) throws Exception {
String content=HttpUtil.get("http://www.apache.org/");
System.out.println(content);
}