根据 url 执行请求,并返回结果。
前提依赖
核心代码
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import net.super0.sellbox.meta.entity.constant.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class HttpRemoteService {
private static final Logger logger = LoggerFactory.getLogger(HttpRemoteService.class);
private static final String DEFAULT_ENCODE = "UTF-8";
private static final String DEFAULT_CONTENT_TYPE = "application/json";
@Autowired
private CloseableHttpClient httpClient;
}
处理 Get 请求
/**
* GET请求处理器
*
* @param url 地址
* @param header 请求头
* @param param 请求参数
* @param clazz 返回类型
* @param <T>
* @return
*/
public <T> T executeGet(String url, Map<String, String> header, Map<String, Object> param, Class<T> clazz) {
T responseResult = null;
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
if (param != null) {
for (Map.Entry<String, Object> entry : param.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
if (header != null && header.size() > 0) {
header.forEach(httpGet::addHeader);
}
log.info("http get 请求url:{}, param:{}", httpGet.getURI(), param);
response = httpClient.execute(httpGet);
String result = EntityUtils.toString(response.getEntity(), Charset.forName(DEFAULT_ENCODE));
// log.info("http get 返回原始值 result:{}", result);
if (StringUtils.isNotEmpty(result)) {
responseResult = JSON.parseObject(result, clazz);
}
} catch (Exception e) {
log.error("executeGet error", e);
} finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
return responseResult;
}
处理 Post 请求
/**
* POST请求处理器
*
* @param url 地址
* @param header 请求头
* @param paramMap 请求参数
* @param jsonParam 请求体
* @param clazz 返回的类型
* @param <T>
* @return
*/
public <T> T executePost(String url, Map<String, String> header, Map<String, Object> paramMap, JSONObject jsonParam,
Class<T> clazz) {
CloseableHttpResponse response = null;
T responseResult = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
// 判断请求参数不为空
if (paramMap != null) {
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 声明httpPost请求
HttpPost httpPost = new HttpPost(uriBuilder.build());
// 判断请求头不为空
if (header != null && header.size() > 0) {
header.forEach(httpPost::addHeader);
}
// 判断请求体不为空
if (jsonParam != null) {
StringEntity entity = new StringEntity(jsonParam.toJSONString(), DEFAULT_ENCODE);
entity.setContentEncoding(DEFAULT_ENCODE);
entity.setContentType(DEFAULT_CONTENT_TYPE);
httpPost.setEntity(entity);
}
// 使用HttpClient发起请求,返回response
response = httpClient.execute(httpPost);
if (response == null) {
return null;
}
String result = EntityUtils.toString(response.getEntity(), Charset.forName(DEFAULT_ENCODE));
if (StringUtils.isNotEmpty(result)) {
responseResult = JSON.parseObject(result, clazz);
}
} catch (Exception e) {
log.error("executePost error", e);
} finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
// 返回结果
return responseResult;
}
GET 获取字节流
/**
* http get 方法获取字节流
*
* @param url
* @return
*/
public byte[] executeGetForBytes(String url) {
byte[] result = null;
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
HttpGet httpGet = new HttpGet(uriBuilder.build());
response = httpClient.execute(httpGet);
result = EntityUtils.toByteArray(response.getEntity());
} catch (Exception e) {
logger.error("executeGet error", e);
} finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
return result;
}
将对象转换为字节流
/**
* 将对象装换为map
*
* @param bean
* @return
*/
private <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = Maps.newHashMap();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
}
return map;
}