1.发送Http 携带 json格式的数据
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashMap;public class HttpClienUtil {private static Logger logger = LoggerFactory.getLogger(HttpClienUtil.class);public static String sandHttpClien(String jsonDataStr,String url){HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();// 请求的 地址HttpPost post = new HttpPost(url);String result = "";try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {// 设置 post 请求参数 json 字符串 形式的//String jsonDataStr = JSON.toJSONString(deviceRegisterVO);// 修复 POST json 导致中文乱码HttpEntity entity = new StringEntity(jsonDataStr,"UTF-8");post.setEntity(entity);post.setHeader("Content-type", "application/json");//发送 请求HttpResponse resp = closeableHttpClient.execute(post);InputStream respIs = resp.getEntity().getContent();byte[] respBytes = IOUtils.toByteArray(respIs);// 接受 并转换 回调的数据result = new String(respBytes, Charset.forName("UTF-8"));//DeviceRegistVO deviceRegistVO = JSON.parseObject(result, DeviceRegistVO.class);} catch (Exception e) {logger.error("HttpClienUtil post报错", e);} finally {return result;}}}
2.发送Http 携带 表单 格式 带 token 的数据
import com.ruoyi.common.utils.uuid.IdUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;public class HttpClienUtil {private static Logger logger = LoggerFactory.getLogger(HttpClienUtil.class);private static final Logger reportLogger = LoggerFactory.getLogger("report-info");// 登录 接口public static String sandHttpClien(Map<String,String> mapData, String url,String token){// reportLogger.info("进入sandHttpClien方法");
// reportLogger.info("参数mapData:" + mapData);
// reportLogger.info("参数url:" + url);
// reportLogger.info("参数token:" + token);String boundary = IdUtils.simpleUUID();HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();// 请求的 地址HttpPost post = new HttpPost(url);String result = "";try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {// 设置 post 请求参数 json 字符串 形式的//String jsonDataStr = JSON.toJSONString(deviceRegisterVO);// 修复 POST json 导致中文乱码
// HttpEntity entity = new StringEntity(jsonDataStr,"UTF-8");
// post.setEntity(entity);
// post.setHeader("Content-type", "application/json");post.addHeader("Content-type", "multipart/form-data; charset=UTF-8; boundary=" + boundary);post.addHeader("Accept", "*/*");post.addHeader("Accept-Encoding", "UTF-8");post.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36");if(token != null){post.addHeader("Authorization", "Bearer " + token);}MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8).setBoundary(boundary);ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));Set keySet = mapData.keySet();for (Object key : keySet) {// 设置请求参数multipartEntityBuilder.addTextBody(key.toString(), mapData.get(key),contentType);}HttpEntity postFormDataBody = multipartEntityBuilder.build();// 请求参数post.setEntity(postFormDataBody);//发送 请求
// reportLogger.info("sandHttpClien方法 发送请求前 ");HttpResponse resp = closeableHttpClient.execute(post);
// reportLogger.info("sandHttpClien方法 发送请求后 ");InputStream respIs = resp.getEntity().getContent();byte[] respBytes = IOUtils.toByteArray(respIs);// 接受 并转换 回调的数据result = new String(respBytes, Charset.forName("UTF-8"));//DeviceRegistVO deviceRegistVO = JSON.parseObject(result, DeviceRegistVO.class);} catch (Exception e) {logger.error("HttpClienUtil post报错", e);reportLogger.error("HttpClienUtil post报错", e);} finally {reportLogger.info("sandHttpClien方法 收到的返回结果: " +result );return result;}}}
3.发送 Http 通过绑定 代理IP和端口的 数据
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
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.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;public class HttpUtil {private static Logger logger = LoggerFactory.getLogger(HttpClienUtil.class);public static String sandHttpClien(String jsonDataStr,String url){// HttpHost proxy = new HttpHost("192.168.110.253",60601);String result = "";// 代理服务器信息HttpHost proxy = new HttpHost("192.168.110.253",60601);// 创建连接管理器并设置代理BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);// 创建HttpClient并设置连接管理器和路由规划器try (CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).setRoutePlanner(routePlanner).build()) {// 创建HTTP GET请求HttpPost request = new HttpPost(url);HttpEntity entity = new StringEntity(jsonDataStr,"UTF-8");request.setEntity(entity);request.setHeader("Content-type", "application/json");// 执行请求并获取响应try (CloseableHttpResponse response = httpClient.execute(request)) {InputStream respIs = response.getEntity().getContent();byte[] respBytes = IOUtils.toByteArray(respIs);// 接受 并转换 回调的数据result = new String(respBytes, Charset.forName("UTF-8"));}} catch (IOException e) {e.printStackTrace();}finally {return result;}}
}
3.发送 Https 带 p12 证书的 数据
import com.ruoyi.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class HttpsUtil {private Logger logger = LoggerFactory.getLogger(HttpsUtil.class);/**客户端证书路径*/private static final ClassPathResource KEY_STORE_CLIENT_PATH = new ClassPathResource("ca/client.p12");/** keystore类型JKS*/private static final String KEY_STORE_TYPE_JKS = "JKS";/** keystore密码*/private static final String KEYSTORE_PASSWORD = "123456";private CloseableHttpClient httpClient;/*** @throws Exception*/public HttpsUtil() {try {KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_JKS);KeyStore trustKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());InputStream instream = KEY_STORE_CLIENT_PATH.getInputStream();try {//密钥库口令keyStore.load(instream, KEYSTORE_PASSWORD.toCharArray());} catch (CertificateException e) {logger.error("加载客户端端可信任证书出错了", e);} finally {try {instream.close();} catch (Exception ignore) {}}SSLContext sslcontext = SSLContexts.custom()//忽略掉对服务器端证书的校验.loadTrustMaterial(new TrustStrategy() {@Overridepublic boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {return true;}}).loadKeyMaterial(keyStore, KEYSTORE_PASSWORD.toCharArray()).build();SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext,new String[]{"TLSv1.1"},null,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);this.httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();} catch (KeyStoreException e) {logger.error("HttpsUtil初始化报错", e);} catch (IOException e) {logger.error("HttpsUtil初始化报错", e);} catch (NoSuchAlgorithmException e) {logger.error("HttpsUtil初始化报错", e);} catch (KeyManagementException e) {logger.error("HttpsUtil初始化报错", e);} catch (UnrecoverableKeyException e) {logger.error("HttpsUtil初始化报错", e);}}/*** 发送post请求** @param url* @param map* @throws Exception*/public String post(String url, Map<String, Object> map) throws Exception {// 声明POST请求HttpPost httpPost = new HttpPost(url);// 判断map不为空if (null != map) {// 声明存放参数的List集合List<NameValuePair> params = new ArrayList<NameValuePair>();// 遍历map,设置参数到list中for (Map.Entry<String, Object> entry : map.entrySet()) {params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));}// 创建form表单对象UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");formEntity.setContentType("Content-Type:application/json");// 把表单对象设置到httpPost中httpPost.setEntity(formEntity);}// 使用HttpClient发起请求,返回responseCloseableHttpResponse response = this.httpClient.execute(httpPost);// 获取实体HttpEntity entity = response.getEntity();// 将实体装成字符串String res = EntityUtils.toString(entity, Charset.defaultCharset());EntityUtils.consume(entity);return res;}/*** 发送POST请求** @param url* @param map* @return* @throws Exception*/public String get(String url, Map<String, Object> map) throws Exception {String params = null;if (null != map) {// 声明存放参数的List集合List<NameValuePair> list = new ArrayList<NameValuePair>();// 遍历map,设置参数到list中for (Map.Entry<String, Object> entry : map.entrySet()) {list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));}// 转化参数params = EntityUtils.toString(new UrlEncodedFormEntity(list, "utf-8"));}url += StringUtils.isNotBlank(params) ? ("?" + params) : "";HttpGet httpGet = new HttpGet(url);// 使用HttpClient发起请求,返回responseCloseableHttpResponse response = this.httpClient.execute(httpGet);// 获取实体HttpEntity entity = response.getEntity();// 将实体装成字符串String res = EntityUtils.toString(entity, Charset.defaultCharset());EntityUtils.consume(entity);response.close();return res;}/*** 发送POST请求(JSON参数)** @param url* @param json* @return* @throws IOException*/public String post(String url, String json) {String res = null;try {// 声明POST请求HttpPost httpPost = new HttpPost(url);// 表示客户端发送给服务器端的数据格式httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");httpPost.setHeader("Accept", "application/json");StringEntity param = new StringEntity(json, ContentType.APPLICATION_JSON);httpPost.setEntity(param);CloseableHttpResponse resp = this.httpClient.execute(httpPost);HttpEntity entity = resp.getEntity();// 将实体装成字符串res = EntityUtils.toString(entity, Charset.defaultCharset());EntityUtils.consume(entity);resp.close();} catch (UnsupportedCharsetException e) {logger.error("HttpsUtil post报错", e);} catch (IOException e) {logger.error("HttpsUtil post报错", e);} catch (ParseException e) {logger.error("HttpsUtil post报错", e);}return res;}}