远程调用工具类 只写了http 的请求
import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
public class HttpClientUtil {
private static final Log logger = LogFactory.getLog(HttpClientUtil.class);
public static Map<String, Object> post(String url, Map<String, Object> map) {
Map<String,String> headerMap = new HashMap();
return postHeader(url,map,headerMap);
}
public static Map<String, Object> get(String url, Map<String, Object> map) {
Map<String,String> headerMap = new HashMap();
return getHeader(url,map,headerMap);
}
public static Map<String, Object> postHeader(String url, Map<String, Object> query,Map<String,String> header) {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(url);
// 我这里利用阿里的fastjson,将Object转换为json字符串;
// (需要导入com.alibaba.fastjson.JSON包)
String jsonString = JSON.toJSONString(query);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
for(String key : header.keySet()){
httpPost.setHeader(key, header.get(key));
}
// 响应模型
CloseableHttpResponse response = null;
String data = "";
HashMap result = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
logger.info("响应状态为:"+response.getStatusLine());
if (responseEntity != null) {
data = EntityUtils.toString(responseEntity);
result = JSON.parseObject(data, HashMap.class);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static Map<String,Object> getHeader(String url, Map<String,Object> query,Map<String,String> header) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet;
// 参数
if (query != null && query.size()>0) {
StringBuffer params = new StringBuffer();
Set<Map.Entry<String,Object>> entrySet = query.entrySet();
for (Map.Entry<String,Object> item: entrySet) {
try {
String itemValue="";
try {
// url中有汉字或特殊字符(非字母和数字的字符例如:{ ,},"等) 转码
itemValue = URLEncoder.encode(valueCast(item.getValue()), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
params.append("&").append(item.getKey()).append("=").append(itemValue);
} catch (Exception e) {
e.printStackTrace();
}
}
String finalParams = params.toString().substring(1,params.length());
url = url + "?" + finalParams;
}
// 创建get请求
logger.info("url:"+url);
httpGet = new HttpGet(url);
if (header != null && header.size()>0) {
for (String key : header.keySet()) {
httpGet.setHeader(key, header.get(key));
}
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httpGet.setConfig(requestConfig);
// 响应模型
CloseableHttpResponse response = null;
HashMap result = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
logger.info("响应状态为:"+response.getStatusLine());
if (responseEntity != null) {
String reslut = EntityUtils.toString(responseEntity);
logger.info("结果集:"+reslut);
result = JSON.parseObject(reslut, HashMap.class);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* @Description 判断数据类型如果是对象就转义一下
* @Date 10:54 2022/8/2
* @Param [value]
* @return java.lang.String
*/
public static String valueCast(Object value) {
String valueString = "";
if(value instanceof Collection) {
return JSON.toJSONString(value);
}else if (value instanceof Map){
return JSON.toJSONString(value);
}else if (value instanceof List){
return JSON.toJSONString(value);
}else {
valueString = String.valueOf(value);
}
return valueString;
}
}