HttpClient sends get request, post request; HttpClient uploads files
package cn.gtmap.ias.datagovern.utils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;
public class HttpClientUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 60000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 60000;
public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
String resultContent = "";
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
// 创建访问的地址
URIBuilder uriBuilder;
try {
uriBuilder = new URIBuilder(url);
if (params != null)
{
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet)
{
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 封装请求头
if (headers != null)
{
Set<Map.Entry<String, String>> entrySet2 = params.entrySet();
for (Map.Entry<String, String> entry : entrySet2)
{
// 设置到请求头到HttpRequestBase对象中
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应数据
resultContent = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("返回结果" + resultContent);
}
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
httpclient.close();
return resultContent;
}
}
public static String doPost(String url, Map<String, String> headers, String jsonString) throws IOException {
String resultContent = "";
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*
* httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
* "keep-alive"); httpPost.setHeader("Accept", "application/json");
* httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
* httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
* httpPost.setHeader("User-Agent",
* "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
* );
*/
// 封装请求头
if (headers != null)
{
Set<Map.Entry<String, String>> entrySet2 = headers.entrySet();
for (Map.Entry<String, String> entry : entrySet2)
{
// 设置到请求头到HttpRequestBase对象中
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
httpPost.setHeader("Content-Type", "application/json");
// 封装请求参数
httpPost.setEntity(new StringEntity(jsonString, ENCODING));
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应数据
resultContent = EntityUtils.toString(response.getEntity(), "UTF-8");
// System.out.println("返回结果:" + resultContent);
logger.info("200返回结果:" + resultContent);
}
if (response != null) {
response.close();
}
httpclient.close();
return resultContent;
}
}
HttpClient sends a Post request for uploading pictures:
/**
*
* @param url
* @param headers
* @param filePath 文件路径
* @param contentType 文件类型
* @param params 接口其它参数
* @return
* @throws IOException
*/
public static String doPost(String url, Map<String, String> headers, String filePath, String contentType, Map<String, String> params) throws IOException {
String resultContent = "";
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*
* httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
* "keep-alive"); httpPost.setHeader("Accept", "application/json");
* httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
* httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
* httpPost.setHeader("User-Agent",
* "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
* );
*/
// 封装请求头
if (headers != null)
{
Set<Map.Entry<String, String>> entrySet2 = headers.entrySet();
for (Map.Entry<String, String> entry : entrySet2)
{
// 设置到请求头到HttpRequestBase对象中
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
FileBody bin;
if (contentType == null){
bin = new FileBody(new File(filePath));
}else {
bin = new FileBody(new File(filePath), contentType);
}
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addPart("file", bin);
if (params != null){
for (String key : params.keySet()) {
StringBody aa = new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8));
multipartEntityBuilder.addPart(key, aa);
}
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httpPost.setEntity(reqEntity);
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应数据
resultContent = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("200返回结果:" + resultContent);
}
if (response != null) {
response.close();
}
httpclient.close();
return resultContent;
}