比如别人给你http://localhost:8080/data/zzz接口地址,你自己的项目需要用到,那怎么做呢。
controller层大概:
public static void main(String[] args) { logger.error("======================================================================="); String result = ""; try { Map<String, Object> params = new HashMap<String, Object>(); params.put("subject", "人力"); params.put("sendAddr", "wangxiaoyang"); result = HttpUtil2.doPost("http://localhost:8080/data/zzz", params,null); //result="{"access_token":"jksdhsdfhd","refresh_token":"","expires_in":1800}"; //okenjson:{"access_token":"","refresh_token":"","expires_in":1800}access_token = Tokenjson.getString("access_token"); JSONObject o=JSONObject.fromObject(result); logger.error(result+"0000000000000000"); } catch (Exception e) { e.printStackTrace(); } }
执行http工具类方法:执行http请求,返回请求的结果
public class HttpUtil {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;
private static Logger logger=Logger.getLogger(HttpUtil.class);
static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
// 在提交请求之前 测试连接是否可用
connMgr.setValidateAfterInactivity(1);
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
requestConfig = configBuilder.build();
}
/**
* 发送POST请求
*
* @param apiUrl
* API接口URL
* @param params
* K-V参数
* @return String 响应内容
*/
public static String doPost(String apiUrl, Map<String, Object> params, Map<String, String> headers) {
return doHttp(apiUrl, params, "post", 2, false, headers);
}
/**
* 发送 http 请求
*
* @param apiUrl
* API接口URL
* @param params
* {Map<String, Object> K-V形式、json字符串}
* @param method
* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}
* @param type
* {1:请求返回stream(此时流需要在外部手动关闭),其余:请求返回字符串}
* @param ssl
* @return {InputStream或者String}
*/
@SuppressWarnings("unchecked")
public static <T> T doHttp(String apiUrl, Object params, String method, int type, boolean ssl,
Map<String, String> headers) {
CloseableHttpClient httpClient = null;
if (ssl) {
/*httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();*/
} else {
httpClient = HttpClients.createDefault();
}
HttpRequestBase httpPost = null;
if (StringUtils.isNotBlank(method)) {
if ("patch".equalsIgnoreCase(method)) {
httpPost = new HttpPatch(apiUrl);
} else if ("delete".equalsIgnoreCase(method)) {
httpPost = new HttpDelete(apiUrl);
} else if ("get".equalsIgnoreCase(method)) {
httpPost = new HttpGet(apiUrl);
} else if ("post".equalsIgnoreCase(method)) {
httpPost = new HttpPost(apiUrl);
}
} else {
httpPost = new HttpPost(apiUrl);
}
CloseableHttpResponse response = null;
try {
if (ssl) {
httpPost.setConfig(requestConfig);
}
// 参数不为null、要处理参数
if (params != null) {
logger.error("params != null==============="+apiUrl);
// get请求拼接在url后面
if (httpPost instanceof HttpGet) {
StringBuffer param = new StringBuffer();
if (params instanceof Map) {
Map<String, Object> paramsConvert = (Map<String, Object>) params;
int i = 0;
for (String key : paramsConvert.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(paramsConvert.get(key));
i++;
}
} else {
param.append("?" + params.toString());
}
apiUrl += param;
httpPost = new HttpGet(apiUrl);
}
// delete请求暂不处理
else if (!(httpPost instanceof HttpDelete)) {
// K-V形式
if (params instanceof Map) {
Map<String, Object> paramsConvert = (Map<String, Object>) params;
List<NameValuePair> pairList = new ArrayList<NameValuePair>(paramsConvert.size());
/* for (Map.Entry<String, Object> entry : paramsConvert.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}*/
for (Iterator<Map.Entry<String, Object>> it = paramsConvert
.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
NameValuePair pair = new BasicNameValuePair(
entry.getKey().toString(), entry.getValue().toString());
pairList.add(pair);
}
((HttpEntityEnclosingRequestBase) httpPost)
.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
}
// json格式
else {
StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
((HttpEntityEnclosingRequestBase) httpPost).setEntity(stringEntity);
}
}
}
// 拼接header
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.addHeader(key, headers.get(key));
}
}
System.out.println("apiUrl==============="+apiUrl);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (type == 1) {
return (T) entity.getContent();
} else {
return (T) EntityUtils.toString(entity, "UTF-8");
}
}
} catch (Exception e) {
//e.printStackTrace();
return null;
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
//e.printStackTrace();
return null;
}
}
}
return null;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
}