package com.sxy.rsademo.utils; import com.alibaba.fastjson.JSON; import com.sxy.rsademo.rsa.RsaUtils; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; 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.util.EntityUtils; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.*; /** * @Description HttpClient 工具类 * @Author SuXingYong * @Date 2020/7/11 23:35 **/ @Slf4j public class HttpClientUtils { /** 目标服务器 - URL - 01 **/ public final static String CLIENT_URL_01 = "http://localhost:9009/target-server/data/receive"; /** 目标服务器 - 数据 - 键名 **/ public final static String SERVER_DATA_KEY = "dataJson"; /** 目标服务器 - 签名 - 键名 **/ public final static String SERVER_SIGN_KEY = "sign"; public static void main(String[] args) { try { String url = ""; Map<String, String> parameterMap = new LinkedHashMap<>(); // 发送数据 Map<String, String> resultMap = HttpClientUtils.sendDataToTargetServerForOne(url,parameterMap); for (Map.Entry<String, String> result : resultMap.entrySet()){ log.info("result==》 "+result.getKey()+": "+result.getValue()); } } catch (Exception e) { e.printStackTrace(); } } /** * @Description 构造数据 * @Author SuXingYong * @Date 2020/7/11 23:35 * @Param [] * @Return java.util.Map<java.lang.String,java.lang.String> **/ public static Map<String,String> createData() throws UnsupportedEncodingException { Map<String, String> returnMap = new LinkedHashMap<>(); Map<String, String> dataMap = new LinkedHashMap<>(); dataMap.put("id","11eh-9b58-af45b5c8-b5e2-9d0036e9473z"); dataMap.put("name","小明"); dataMap.put("loginName","xiaoming"); dataMap.put("phone","12345678901"); dataMap.put("time","2020-07-12 00:33:27"); dataMap.put("content","随便整了些内容,就验证一下。"); for (Map.Entry<String, String> data : dataMap.entrySet()){ returnMap.put(data.getKey(),URLEncoder.encode(data.getValue(),"UTF-8")); } return returnMap; } /** * @Description 单条发送数据 * @Author SuXingYong * @Date 2020/7/11 23:35 * @Param [url,parameterMap] * @Return java.util.Map<java.lang.String,java.lang.String> **/ public static Map<String, String> sendDataToTargetServerForOne(String url,Map<String, String> parameterMap) throws Exception { // 返回结果集 Map<String, String> returnMap = new LinkedHashMap<>(); // 请求参数 传入参数结果集为空的时候就直接使用默认值 Map<String, String> requestMap = HttpClientUtils.createData(); if (parameterMap != null && parameterMap.size() >0){ // 清空默认值 requestMap = new LinkedHashMap<>(); // 对参数集合的值进行url编码 for (Map.Entry<String, String> param : parameterMap.entrySet()){ requestMap.put(param.getKey(),URLEncoder.encode(param.getValue(),"UTF-8")); } } if (requestMap != null && requestMap.size() >0){ // 数据参数字符串 StringBuilder dataStr = new StringBuilder(""); // 遍历参数集合并拼接成字符串 for (Map.Entry<String, String> map : requestMap.entrySet()){ // 键名 String dataKey = map.getKey(); // 键值 String dataValue = map.getValue(); dataStr.append(dataKey).append("="); dataStr.append(dataValue); dataStr.append("&"); } log.info("send==》 dataStr:"+dataStr); // 去除最后一个&符号 String paramStr = dataStr.toString().substring(0, dataStr.length() - 1); log.info("send==》 paramStr:"+paramStr); // 服务器原文数据 //requestMap.put("originalTextData",paramStr); // 将数据转化为json字符串 String dataJson = JSON.toJSONString(requestMap); log.info("send==》 dataJson: "+dataJson); // 重置请求参数集合 requestMap = new LinkedHashMap<>(); // 将json数据放到请求参数集合中 //requestMap.put("data",dataJson); // 密钥对 Map<String,Object> keyMap = RsaUtils.getLastingKeyPair(); // 使用持久化公钥对数据进行加密 String cipherTextData = RsaUtils.encryptByPublicKey(dataJson, CastUtils.castString(keyMap.get(RsaUtils.PUBLIC_KEY))); log.info("send==》 cipherTextData: "+cipherTextData); // 服务器密文数据 requestMap.put("data",cipherTextData); // 使用持久化私钥生成签名 String sign = RsaUtils.generatorSign(cipherTextData, CastUtils.castString(keyMap.get(RsaUtils.PRIVATE_KEY))); // log.info("send==》 sign: "+sign); // 请求参数中需带上签名字符串 requestMap.put(SERVER_SIGN_KEY, sign); // 将请求参数转化为json字符串 String requestJson = JSON.toJSONString(requestMap); log.info("send==》 requestJson:"+requestJson); // 请求地址 没有传入的时候就使用默认值 String requestUrl = CLIENT_URL_01; if (url != null && url != ""){ requestUrl = url; log.info("send==》 requestUrl:"+requestUrl); } if (requestUrl != null && requestUrl != ""){ requestMap = new LinkedHashMap<>(); requestMap.put(SERVER_DATA_KEY, requestJson); if (requestMap != null && requestMap.size() >0){ //发送POST请求 parameterMap模式 returnMap = HttpClientUtils.sendPostRequest(requestUrl,requestMap); }else{ returnMap.put(ReturnConstant.ERROR,"请求数据参数为空,不支持"); } //if (requestJson != null && requestJson != ""){ // 发送POST请求 json模式 // returnMap = HttpClientUtils.sendPostRequest(requestUrl,requestJson); //}else{ // returnMap.put(ReturnConstant.ERROR,"请求数据参数为空,不支持"); //} }else{ returnMap.put(ReturnConstant.ERROR,"请求地址为空,不支持"); } }else{ returnMap.put(ReturnConstant.ERROR,"发送数据为空,不支持"); } return returnMap; } /** * @Description 批量发送数据 * @Author SuXingYong * @Date 2020/7/11 23:35 * @Param [url, dataList] * @Return java.util.Map<java.lang.String,java.lang.String> **/ public static Map<String,String> sendDataToTargetServerForList(String url, List<Map<String,String>> dataList) throws Exception{ // 返回结果集 Map<String, String> returnMap = new LinkedHashMap<>(); // 请求参数集合 Map<String, String> requestMap = new LinkedHashMap<>(); if (dataList != null && dataList.size() >0){ // 缓存列表 List<Map<String, String>> cacheList = new ArrayList<>(); for (int i = 0 ; i < dataList.size() ; i++){ // 对参数进行编码之后的新集合 Map<String, String> newDataMap = new LinkedHashMap<>(); Map<String, String> dataMap = dataList.get(i); // 对参数集合的值进行url编码 for (Map.Entry<String, String> data : dataMap.entrySet()){ newDataMap.put(data.getKey(),URLEncoder.encode(data.getValue(),"UTF-8")); } if (newDataMap != null && newDataMap.size() >0){ // 将编码后的新集合放到缓存数组中 cacheList.add(newDataMap); } } if (cacheList != null && cacheList.size() >0){ // 重置数据列表 dataList = new ArrayList<>(); dataList = cacheList; } // 将数据转化为json字符串 String dataJson = JSON.toJSONString(dataList); log.info("send==》 dataJson: "+dataJson); // 将数据json字符串放到请求参数中 //requestMap.put("originalTextData",dataJson); // 密钥对 Map<String,Object> keyMap = RsaUtils.getLastingKeyPair(); // 使用持久化公钥对数据进行加密 String cipherTextData = RsaUtils.encryptByPublicKey(dataJson, CastUtils.castString(keyMap.get(RsaUtils.PUBLIC_KEY))); log.info("send==》 cipherTextData: "+cipherTextData); // 发送密文数据 requestMap.put("data",cipherTextData); // 使用持久化私钥生成签名 String sign = RsaUtils.generatorSign(cipherTextData, CastUtils.castString(keyMap.get(RsaUtils.PRIVATE_KEY))); // log.info("send==》 sign: "+sign); // 请求参数中需带上签名字符串 requestMap.put(SERVER_SIGN_KEY, sign); // 将请求参数转化为json字符串 String requestJson = JSON.toJSONString(requestMap); log.info("send==》 requestJson:"+requestJson); // 请求地址 没有传入的时候就使用默认值 String requestUrl = CLIENT_URL_01; if (url != null && url != ""){ requestUrl = url; log.info("send==》 requestUrl:"+requestUrl); } if (requestUrl != null && requestUrl != ""){ if (requestJson != null && requestJson != ""){ // 发送POST请求 json模式 returnMap = HttpClientUtils.sendPostRequest(requestUrl,requestJson); }else{ returnMap.put(ReturnConstant.ERROR,"请求数据参数为空,不支持"); } }else { returnMap.put(ReturnConstant.ERROR, "请求地址为空,不支持"); } }else{ returnMap.put(ReturnConstant.ERROR,"数据为空,不支持"); } return returnMap; } /** * @Description 发送POST请求 parameterMap模式 * @Author SuXingYong * @Date 2020/7/11 23:35 * @Param [url, json] * @Return java.util.Map<java.lang.String,java.lang.String> **/ public static Map<String, String> sendPostRequest(String url,Map<String, String> parameterMap){ // 返回结果 Map<String, String> returnMap = new LinkedHashMap<>(); OutputStream out = null; BufferedReader in = null; HttpURLConnection conn = null; String result = ""; try { StringBuilder data = new StringBuilder(); for (Map.Entry<String, String> dataKeyValue : parameterMap.entrySet()) { String dataName = dataKeyValue.getKey(); String dataValue = dataKeyValue.getValue(); data.append(dataName).append("="); //data.append(dataValue); // 转换为UTF-8编码 data.append(URLEncoder.encode(dataValue, "UTF-8")); data.append("&"); } data.append("sendTime=").append(System.currentTimeMillis()); log.info("send==》 parameterMapStr: "+data.toString()); byte[] entity = data.toString().getBytes(); conn = (HttpURLConnection)new URL(url).openConnection(); conn.setUseCaches(false); // 10000 conn.setConnectTimeout(10000); // POST conn.setRequestMethod("POST"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); out = conn.getOutputStream(); // 获取URLConnection对象对应的输出流 out = conn.getOutputStream(); // 发送请求参数 out.write(entity); // flush输出流的缓冲 out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } returnMap.put(ReturnConstant.SUCCESS,result); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return returnMap; } /** * @Description 发送POST请求 json字符串模式 * @Author SuXingYong * @Date 2020/7/11 23:35 * @Param [url, json] * @Return java.util.Map<java.lang.String,java.lang.String> **/ public static Map<String, String> sendPostRequest(String url,String json){ // 返回结果集 Map<String, String> returnMap = new LinkedHashMap<>(); // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); log.info("send==》 json:"+json); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); returnMap.put(ReturnConstant.SUCCESS, EntityUtils.toString(response.getEntity(), "utf-8")); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return returnMap; } /** * 获取sendPostRequest请求的Json数据 */ private String getRequestPostData(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if (contentLength < 0) { return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength;) { int len = request.getInputStream().read(buffer, i, contentLength - i); if (len == -1) { break; } i += len; } return new String(buffer, "utf-8"); } }
HttpClientUtils.javaSpringBoot项目运行入口类: