TRX 1 жил өмнө
parent
commit
af0086b0c2

+ 67 - 0
src/main/java/com/zswl/dataservice/httpRequest/ApiRequestService.java

@@ -0,0 +1,67 @@
+package com.zswl.dataservice.httpRequest;
+
+import cn.hutool.core.bean.BeanUtil;
+import cn.hutool.json.JSONUtil;
+import com.zswl.dataservice.httpRequest.apiConf.APIResponseModel;
+import com.zswl.dataservice.httpRequest.apiConf.ApiConfParam;
+import com.zswl.dataservice.httpRequest.conf.FullCardAPIConfig;
+import com.zswl.dataservice.httpRequest.conf.FullCardConf;
+import com.zswl.dataservice.service.base.SuperService;
+import com.zswl.dataservice.utils.net.apache.HttpClientUtil;
+import com.zswl.dataservice.utils.net.apache.HttpModel;
+import com.zswl.dataservice.utils.net.apache.ResponseModel;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.ObjectUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author TRX
+ * @date 2024/6/25
+ */
+@Slf4j
+@Service
+public class ApiRequestService extends SuperService {
+
+    @Autowired
+    FullCardConf fullCardConf;
+
+    /**
+     * 发送请求
+     *
+     * @param apiName
+     * @param data
+     * @return
+     */
+    public APIResponseModel sendFullCardAPI(String apiName, Object data) {
+        APIResponseModel responseModel = new APIResponseModel();
+        if (StringUtils.isEmpty(fullCardConf.getUrl())) {
+            responseModel.setIsFailed("未配置物联网平台URL");
+            return responseModel;
+        }
+        try {
+            ApiConfParam apiConfParam = FullCardAPIConfig.getApiConfParam(apiName);
+            if (ObjectUtils.isEmpty(apiConfParam)) {
+                responseModel.setIsFailed("未找到API配置");
+                return responseModel;
+            }
+            String json = JSONUtil.toJsonStr(data);
+            String url = fullCardConf.getUrl() + apiConfParam.getApiName();
+            ResponseModel request = HttpClientUtil.request(HttpModel.builder()
+                    .url(url).method(apiConfParam.getMethodType()).charset("utf-8").body(data).build());
+            if (request.getCode() == 200) {
+                responseModel = BeanUtil.copyProperties(request.getBody(), APIResponseModel.class);
+            } else {
+                responseModel = BeanUtil.copyProperties(request.getBody(), APIResponseModel.class);
+            }
+            responseModel.setParam(apiConfParam);
+        } catch (Exception e) {
+            e.printStackTrace();
+            responseModel.setIsFailed(String.format("请求出错:%s", e.getMessage()));
+            return responseModel;
+        }
+        return responseModel;
+    }
+
+}

+ 45 - 0
src/main/java/com/zswl/dataservice/httpRequest/apiConf/APIResponseModel.java

@@ -0,0 +1,45 @@
+package com.zswl.dataservice.httpRequest.apiConf;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * @author TRX
+ * @date 2024/6/25
+ */
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class APIResponseModel {
+    private boolean failed;
+    private boolean success;
+    private String msg;
+    private String state;
+    private String content;
+
+    private ApiConfParam param;
+
+    public boolean isSuccess() {
+        if (StringUtils.isNotEmpty(this.state) && "Fail".equals(state)) {
+            return failed;
+        }
+        return success;
+    }
+
+    public boolean isFailed() {
+        return !this.isSuccess();
+    }
+
+    public void setIsFailed() {
+        this.success = Boolean.FALSE;
+        this.failed = Boolean.TRUE;
+        this.state = "Fail";
+    }
+
+    public void setIsFailed(String msg) {
+        this.setIsFailed();
+        this.msg = msg;
+    }
+}

+ 26 - 0
src/main/java/com/zswl/dataservice/httpRequest/apiConf/ApiConfParam.java

@@ -0,0 +1,26 @@
+package com.zswl.dataservice.httpRequest.apiConf;
+
+import com.zswl.dataservice.utils.net.apache.MethodType;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * @author TRX
+ * @date 2024/6/25
+ */
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class ApiConfParam {
+
+    @Schema(description = "API名称")
+    private String apiName;
+
+    @Schema(description = "方式")
+    private MethodType methodType;
+
+}

+ 35 - 0
src/main/java/com/zswl/dataservice/httpRequest/conf/FullCardAPIConfig.java

@@ -0,0 +1,35 @@
+package com.zswl.dataservice.httpRequest.conf;
+
+import com.zswl.dataservice.httpRequest.apiConf.ApiConfParam;
+import com.zswl.dataservice.utils.net.apache.MethodType;
+
+import java.util.HashMap;
+
+/**
+ * 物联网平台的 APIP诶这
+ *
+ * @author TRX
+ * @date 2024/6/25
+ */
+public class FullCardAPIConfig {
+
+    // 测试发送消息
+    public static final String sendMessage = "/mqttMessage/sendMessage";
+
+    public static final String ping = "/test/free/ping";
+
+    public static final HashMap<String, ApiConfParam> map = new HashMap<>();
+
+    static {
+        map.put(sendMessage, ApiConfParam.builder().apiName(sendMessage).methodType(MethodType.Json).build());
+        map.put(ping, ApiConfParam.builder().apiName(ping).methodType(MethodType.Get).build());
+
+
+
+    }
+
+    public static ApiConfParam getApiConfParam(String apiName) {
+        return map.get(apiName);
+    }
+
+}

+ 19 - 0
src/main/java/com/zswl/dataservice/httpRequest/conf/FullCardConf.java

@@ -0,0 +1,19 @@
+package com.zswl.dataservice.httpRequest.conf;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@NoArgsConstructor
+@AllArgsConstructor
+@ConfigurationProperties(prefix = "fullcard")
+public class FullCardConf {
+    /**
+     * 全卡业务平台平台地址配置
+     */
+    private String url = "";
+}

+ 2 - 0
src/main/java/com/zswl/dataservice/httpRequest/package-info.java

@@ -0,0 +1,2 @@
+package com.zswl.dataservice.httpRequest;
+//物联网平台的相关配置

+ 13 - 1
src/main/java/com/zswl/dataservice/service/user/impl/UserServiceImpl.java

@@ -5,6 +5,9 @@ import com.google.gson.JsonObject;
 import com.zswl.dataservice.config.SystemDefaultConfig;
 import com.zswl.dataservice.dao.UserDao;
 import com.zswl.dataservice.domain.user.User;
+import com.zswl.dataservice.httpRequest.ApiRequestService;
+import com.zswl.dataservice.httpRequest.apiConf.APIResponseModel;
+import com.zswl.dataservice.httpRequest.conf.FullCardAPIConfig;
 import com.zswl.dataservice.model.mqtt.SendMessageModel;
 import com.zswl.dataservice.model.user.UpdateUserPassWordParam;
 import com.zswl.dataservice.model.user.UserInfoModel;
@@ -55,6 +58,9 @@ public class UserServiceImpl extends SuperService implements UserService {
     @Autowired
     UserManagerServiceImpl userManagerService;
 
+    @Autowired
+    ApiRequestService apiRequestService;
+
     /**
      * 初始超级管理员
      *
@@ -180,12 +186,18 @@ public class UserServiceImpl extends SuperService implements UserService {
             jsonObject.addProperty("data", param.getMessage());
             jsonObject.addProperty("time", DateUtils.paresTime(System.currentTimeMillis(), DateUtils.patternyyyySSS));
             jsonObject.addProperty("ttl", 10 * 1000);
-            mqClient.sendObject(param.getTopic(), jsonObject.toString());
+//            mqClient.sendObject(param.getTopic(), jsonObject.toString());
             log.info("mqtt msg 发送成功");
         } catch (Exception e) {
             e.printStackTrace();
             msg = "发送失败: " + e.getMessage();
         }
+        APIResponseModel resultContent = apiRequestService.sendFullCardAPI(
+                FullCardAPIConfig.sendMessage, param);
+        if (resultContent.isSuccess()) {
+
+        }
+        log.info("是否成功: {} {} {}", resultContent.isSuccess(), resultContent.getContent(), resultContent.getMsg());
         return ResultContent.buildSuccess(msg);
     }
 

+ 463 - 0
src/main/java/com/zswl/dataservice/utils/net/HttpClient.java

@@ -0,0 +1,463 @@
+package com.zswl.dataservice.utils.net;
+
+import lombok.SneakyThrows;
+
+import javax.net.ssl.*;
+import java.io.*;
+import java.net.*;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ * Http client
+ *
+ * @作者:练书锋 @日期:2013年10月22日
+ *
+ */
+public class HttpClient {
+
+	static {
+		init();
+	}
+
+	@SneakyThrows
+	private static void init(){
+		SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");//第一个参数为协议,第二个参数为提供者(可以缺省)
+		TrustManager[] tm = {new X509TrustManager(){
+
+			@Override
+			public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+
+			}
+
+			@Override
+			public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+
+			}
+
+			@Override
+			public X509Certificate[] getAcceptedIssuers() {
+				return new X509Certificate[0];
+			}
+		}};
+		sslcontext.init(null, tm, new SecureRandom());
+		HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
+			public boolean verify(String s, SSLSession sslsession) {
+				System.out.println("WARNING: Hostname is not matched for cert.");
+				return true;
+			}
+		};
+		HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
+		HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
+	}
+
+	private static final String CHARSET = "charset";
+
+	// 连接超时时间
+	private int connectTimeout = 60000;
+	// 读取超时时间
+	private int readTimeout = 60000;
+	// cookies
+	private Map<String, String> cookies = new HashMap<String, String>();
+	// 设置是否自动跳转
+	private boolean followRedirects = true;
+
+	// 监听输出管道
+	private OutputStream listenOutputStream;
+
+	// 代理IP
+	private String proxyHost;
+	// 代理端口
+	private int porxyPort;
+
+	public OutputStream getListenOutputStream() {
+		return listenOutputStream;
+	}
+
+	public HttpClient setListenOutputStream(OutputStream listenOutputStream) {
+		this.listenOutputStream = listenOutputStream;
+		return this;
+	}
+
+	public boolean isFollowRedirects() {
+		return followRedirects;
+	}
+
+	public HttpClient setFollowRedirects(boolean followRedirects) {
+		this.followRedirects = followRedirects;
+		return this;
+	}
+
+	public Map<String, String> getCookies() {
+		return cookies;
+	}
+
+	public HttpClient setCookies(Map<String, String> cookies) {
+		this.cookies = cookies;
+		return this;
+	}
+
+	public int getConnectTimeout() {
+		return connectTimeout;
+	}
+
+	public HttpClient setConnectTimeout(int connectTimeout) {
+		this.connectTimeout = connectTimeout;
+		return this;
+	}
+
+	public int getReadTimeout() {
+		return readTimeout;
+	}
+
+	public void setReadTimeout(int readTimeout) {
+		this.readTimeout = readTimeout;
+	}
+
+	public String getProxyHost() {
+		return proxyHost;
+	}
+
+	public HttpClient setProxyHost(String proxyHost) {
+		this.proxyHost = proxyHost;
+		return this;
+	}
+
+	public int getPorxyPort() {
+		return porxyPort;
+	}
+
+	public HttpClient setPorxyPort(int porxyPort) {
+		this.porxyPort = porxyPort;
+		return this;
+	}
+
+	/**
+	 * 默认的构造方法
+	 */
+	public HttpClient() {
+
+	}
+
+	/**
+	 * 请重写该方法用于显示下载进度
+	 *
+	 * @param currentPoint
+	 * @param totalPoint
+	 */
+	public void showProgress(long currentPoint, long totalPoint) {
+
+	}
+
+	/**
+	 * 使用get方式请求
+	 *
+	 * @param url
+	 * @return
+	 * @throws IOException
+	 */
+	public byte[] get(final String url) throws IOException {
+		return ReadDocuments(url, false, null).getData();
+	}
+
+	/**
+	 * 使用POST请求
+	 *
+	 * @param url
+	 * @param bin
+	 * @return
+	 * @throws IOException
+	 */
+	public byte[] post(final String url, final byte[] bin) throws IOException {
+		return ReadDocuments(url, true, bin).getData();
+	}
+
+	/**
+	 * 请求网络访问
+	 *
+	 * @param url
+	 * @return
+	 * @throws IOException
+	 */
+	public ResultBean ReadDocuments(String url) throws IOException {
+		return ReadDocuments(url, false, null);
+	}
+
+	/**
+	 *
+	 * @param url
+	 * @param isPost
+	 * @param
+	 * @return
+	 * @throws IOException
+	 */
+	public ResultBean ReadDocuments(String url, boolean isPost, byte[] postData) throws IOException {
+		return ReadDocuments(new URL(url), isPost, postData, null, null);
+	}
+
+	/**
+	 * HTTP访问网络
+	 *
+	 * @param url
+	 * @param isPost
+	 * @param postData
+	 * @param requestHead
+	 * @return
+	 * @throws IOException
+	 */
+	public ResultBean ReadDocuments(String url, boolean isPost, byte[] postData, Map<String, String> requestHead)
+			throws IOException {
+		return ReadDocuments(new URL(url), isPost, postData, requestHead, null);
+	}
+
+
+	public ResultBean ReadDocuments(final URL url, final boolean isPost, final byte[] postData,
+			Map<String, String> requestHead, Boolean onlyHead) throws IOException {
+		HttpURLConnection httpURLConnection = connect(url, isPost, requestHead);
+		if (httpURLConnection == null) {
+			return null;
+		}
+		// 写出参数
+		if (isPost && postData != null) {
+			OutputStream outputStream = httpURLConnection.getOutputStream();
+			outputStream.write(postData);
+			outputStream.flush();
+			outputStream.close();
+		}
+		// 设置响应与返回的响应头信息
+		ResultBean resultBean = readInputStream(httpURLConnection, onlyHead);
+		// 设置服务器需要设置的cookies
+		readAndSetCookies(httpURLConnection);
+		return resultBean;
+	}
+
+	/**
+	 * 创建连接管道
+	 *
+	 * @param url
+	 * @param isPost
+	 * @param requestHead
+	 * @return 返回写入的数据管道
+	 * @throws IOException
+	 */
+	protected HttpURLConnection connect(final URL url, final Boolean isPost, Map<String, String> requestHead)
+			throws IOException {
+		URLConnection uRLConnection = null;
+		if (this.proxyHost == null) {
+			uRLConnection = url.openConnection();
+		} else {
+			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.porxyPort));
+			uRLConnection = url.openConnection(proxy);
+		}
+		HttpURLConnection httpURLConnection = (HttpURLConnection) uRLConnection;
+		// 设置是否自动重定向
+		httpURLConnection.setInstanceFollowRedirects(isFollowRedirects());
+		// 设置访问模式
+		httpURLConnection.setRequestMethod(isPost != null && isPost ? "POST" : "GET");
+		// 设置是否从httpUrlConnection读入,默认情况下是true;
+		httpURLConnection.setDoInput(true);
+		// http正文内,因此需要设为true, 默认情况下是false;
+		httpURLConnection.setDoOutput(true);
+		// Post 请求不能使用缓存
+		httpURLConnection.setUseCaches(false);
+		// 请求头
+		if (requestHead == null) {
+			requestHead = new HashMap<String, String>();
+		}
+		// 设置请求类型编码
+		if (requestHead.get("Content-type") == null) {
+			httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
+		}
+		// 设置浏览器的版本
+		if (requestHead.get("User-Agent") == null) {
+			httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
+		}
+		// 设置默认的Referer
+		if (requestHead.get("Referer") == null) {
+			httpURLConnection.setRequestProperty("Referer", url.toExternalForm());
+		}
+
+		for (String key : requestHead.keySet()) {
+			httpURLConnection.setRequestProperty(key, requestHead.get(key));
+		}
+
+		// 加载cookies
+		if (this.cookies != null && this.cookies.size() > 0)
+			httpURLConnection.setRequestProperty("Cookie", getInnerCookies());
+
+		httpURLConnection.setConnectTimeout(connectTimeout);
+		httpURLConnection.setReadTimeout(readTimeout);
+		// 开始连接连接
+		httpURLConnection.connect();
+		// 返回该创建连接后的对象
+		return httpURLConnection;
+	}
+
+	/**
+	 * 取响应的结果
+	 *
+	 * @param httpURLConnection
+	 * @return
+	 * @throws IOException
+	 */
+	protected ResultBean readInputStream(HttpURLConnection httpURLConnection, Boolean onlyHead) throws IOException {
+		// 读取响应的数据
+		InputStream inputStream = null;
+		try {
+			inputStream = httpURLConnection.getInputStream();
+		} catch (Exception e) {
+			inputStream = httpURLConnection.getErrorStream();
+		}
+		long totalByte = -1;
+		if (httpURLConnection.getHeaderField("Content-Length") != null) {
+			totalByte = Long.parseLong(httpURLConnection.getHeaderField("Content-Length"));
+		}
+		ResultBean resultBean = new ResultBean();
+		// 判断是否读取内容
+		if (onlyHead == null || onlyHead == false) {
+			byte[] resultBin = null;
+			if (inputStream != null) {
+				// 读取内容部分
+				resultBin = inputStreamToBytes(inputStream, totalByte);
+				inputStream.close();
+			}
+			resultBean.setData(resultBin);
+		}
+		// 设置响应的头信息
+		resultBean.setResponseHead(httpURLConnection.getHeaderFields());
+		// 设置响应状态code
+		resultBean.setStat(httpURLConnection.getResponseCode());
+		return resultBean;
+	}
+
+	/**
+	 * 设置当前网络访问后的cookies
+	 *
+	 * @param httpURLConnection
+	 */
+	protected void readAndSetCookies(HttpURLConnection httpURLConnection) {
+		setInnerCookies(httpURLConnection.getHeaderFields().get("Set-Cookie"));
+	}
+
+	private void setInnerCookies(List<String> cookiesStr) {
+		if (cookiesStr != null)
+			for (int i = 0; i < cookiesStr.size(); i++) {
+				String tempStr = cookiesStr.get(i);
+				tempStr = tempStr.replaceAll(";", "=");
+				String[] mapping = tempStr.split("=");
+				if (mapping.length > 1) {
+					String key = mapping[0];
+					String value = mapping[1];
+					this.cookies.put(key, value);
+				}
+			}
+	}
+
+	public String getInnerCookies() {
+		String result = "";
+		for (String key : this.cookies.keySet()) {
+			result += key + "=" + this.cookies.get(key) + "; ";
+		}
+		return result.trim();
+	}
+
+	/**
+	 *
+	 * @param inputStream
+	 * @return
+	 */
+	private byte[] inputStreamToBytes(InputStream inputStream, long totalByte) throws IOException {
+		byte[] container = new byte[102400];
+		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
+		int b = -1;
+		while ((b = inputStream.read(container)) != -1) {
+			if (listenOutputStream != null) {
+				try {
+					listenOutputStream.write(container, 0, b);
+				} catch (Exception e) {
+					e.printStackTrace();
+				}
+			}
+			arrayOutputStream.write(container, 0, b);
+			showProgress(arrayOutputStream.size(), totalByte);
+		}
+		arrayOutputStream.flush();
+		byte[] data = arrayOutputStream.toByteArray();
+		arrayOutputStream.close();
+		return data;
+	}
+
+	/**
+	 * 返回结果集
+	 *
+	 * @author admin
+	 *
+	 */
+	public class ResultBean implements Serializable {
+		/**
+		 *
+		 */
+		private static final long serialVersionUID = 2933585102741021542L;
+
+		public ResultBean() {
+
+		}
+
+		private byte[] data;
+
+		private Map<String, List<String>> responseHead;
+
+		private int stat = 0;
+
+		public int getStat() {
+			return stat;
+		}
+
+		public void setStat(int stat) {
+			this.stat = stat;
+		}
+
+		public byte[] getData() {
+			return data;
+		}
+
+		public void setData(byte[] data) {
+			this.data = data;
+		}
+
+		public Map<String, List<String>> getResponseHead() {
+			return responseHead;
+		}
+
+		public void setResponseHead(Map<String, List<String>> responseHead) {
+			this.responseHead = responseHead;
+		}
+
+		/**
+		 * 取出字符编码,没有则返回null
+		 *
+		 * @return
+		 */
+		public String getCharset() {
+			String charset = null;
+			// 取出文字编码
+			List<String> contentTypes = this.getResponseHead().get("Content-Type");
+			if (contentTypes != null) {
+				for (String contentType : contentTypes) {
+					int at = contentType.indexOf(CHARSET + "=");
+					if (at > -1) {
+						String right = contentType.substring(at + CHARSET.length() + 1, contentType.length());
+						charset = right.trim();
+					}
+				}
+			}
+			return charset;
+		}
+	}
+
+}

+ 96 - 0
src/main/java/com/zswl/dataservice/utils/net/IPUtil.java

@@ -0,0 +1,96 @@
+package com.zswl.dataservice.utils.net;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 取ip的工具
+ */
+public class IPUtil {
+
+
+    /**
+     * 可能出现用户真实ip的头
+     */
+    public final static String[] headNames = new String[]{
+            "X-FORWARDED-FOR",
+            "Proxy-Client-IP",
+            "WL-Proxy-Client-IP",
+            "HTTP_CLIENT_IP",
+            "HTTP_X_FORWARDED_FOR"
+    };
+
+
+    /**
+     * 获取远程ip
+     *
+     * @param request
+     * @return
+     */
+    public static String getRemoteIp(HttpServletRequest request) {
+        final Map<String,String> header = new HashMap();
+        Arrays.stream(headNames).forEach((name) -> {
+            header.put(name, request.getHeader(name));
+        });
+        return getRemoteIp(header, request.getRemoteAddr());
+    }
+
+
+    /**
+     * 获取远程ip
+     *
+     * @return
+     */
+    public static String getRemoteIp(Map<String,String> headers, String defaultRemoteAddr) {
+        for (String name : headNames) {
+            Object obj = headers.get(name);
+            if (obj == null || "".equals(String.valueOf(obj))) {
+                continue;
+            }
+
+            String ip = String.valueOf(obj);
+            int at = ip.indexOf(",");
+            if (at > -1) {
+                ip = ip.substring(0, at);
+            }
+            return ip;
+        }
+        return defaultRemoteAddr;
+    }
+
+
+    /**
+     * ip地址转换为十进制
+     *
+     * @return
+     */
+    public static long ipv4ToLong(String ip) {
+        String[] ips = ip.split("\\.");
+        long result = 0;
+        for (int i = 0; i < ips.length; i++) {
+            int power = 3 - i;
+            result += Integer.parseInt(ips[i]) * Math.pow(256, power);
+        }
+        return result;
+    }
+
+
+    /**
+     * long 转换为 ip
+     *
+     * @param i
+     * @return
+     */
+    public static String longToIpv4(long i) {
+        return ((i >> 24) & 0xFF) +
+                "." + ((i >> 16) & 0xFF) +
+                "." + ((i >> 8) & 0xFF) +
+                "." + (i & 0xFF);
+
+    }
+
+
+}

+ 91 - 0
src/main/java/com/zswl/dataservice/utils/net/JsonUtil.java

@@ -0,0 +1,91 @@
+package com.zswl.dataservice.utils.net;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import org.springframework.util.StreamUtils;
+
+import java.io.InputStream;
+
+/**
+ * json工具
+ *
+ * @作者 练书锋
+ * @联系 oneday@vip.qq.com
+ * @时间 2014年5月17日
+ */
+public class JsonUtil {
+
+    private static ObjectMapper objectMapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
+
+    static {
+        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+    }
+
+    /**
+     * 转换到json字符串
+     *
+     * @param object
+     * @return
+     * @throws Exception
+     */
+    public static String toJson(Object object, boolean format) {
+        try {
+            ObjectWriter objectWriter;
+            if (format) {
+                return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
+            } else {
+                return objectMapper.writeValueAsString(object);
+            }
+        } catch (JsonProcessingException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * 转换到json字符串
+     *
+     * @param object
+     * @return
+     */
+    public static String toJson(Object object) {
+        return toJson(object, false);
+    }
+
+
+    /**
+     * 转换为对象
+     *
+     * @param json
+     * @param cls
+     * @return
+     * @throws Exception
+     */
+    public static <T> T toObject(String json, Class<T> cls) throws Exception {
+        return objectMapper.readValue(json, cls);
+    }
+
+    /**
+     * 载入文件到对象
+     *
+     * @param configName
+     * @param cls
+     * @return
+     * @throws Exception
+     */
+    public static <T> T loadToObject(String configName, Class<T> cls) throws Exception {
+        T t = null;
+        InputStream inputStream = JsonUtil.class.getClassLoader().getResourceAsStream(configName);
+        byte[] bin = StreamUtils.copyToByteArray(inputStream);
+        String json = new String(bin, "UTF-8");
+        t = toObject(json, cls);
+        inputStream.close();
+        return t;
+    }
+
+
+}

+ 267 - 0
src/main/java/com/zswl/dataservice/utils/net/apache/HttpClientUtil.java

@@ -0,0 +1,267 @@
+package com.zswl.dataservice.utils.net.apache;
+
+import com.zswl.dataservice.utils.net.JsonUtil;
+import lombok.Cleanup;
+import lombok.SneakyThrows;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.http.Header;
+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.client.methods.HttpRequestBase;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+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.ssl.SSLContexts;
+import org.springframework.cglib.beans.BeanMap;
+import org.springframework.util.StreamUtils;
+
+import javax.net.ssl.SSLContext;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.*;
+
+@Slf4j
+public class HttpClientUtil {
+
+
+    /**
+     * 网络请求
+     *
+     * @param httpModel
+     * @return
+     * @throws IOException
+     */
+    public static ResponseModel request(HttpModel httpModel) throws IOException {
+        Map<String, Set<Object>> headers = new HashMap<>();
+        @Cleanup ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        Integer code = request(httpModel, byteArrayOutputStream, headers);
+        byte[] content = byteArrayOutputStream.toByteArray();
+        Object body = getBody(headers, content);
+        return ResponseModel.builder().headers(headers).body(body).code(code).build();
+    }
+
+
+    /**
+     * 构建响应
+     *
+     * @return
+     */
+    public static Map<String, Object> buildResponse(Map<String, Set<Object>> headers, Object body) {
+        return new HashMap<String, Object>() {{
+            put("headers", headers);
+            put("body", body);
+        }};
+    }
+
+
+    /**
+     * 网络请求
+     *
+     * @param httpModel
+     * @param outputStream
+     * @return
+     */
+    @SneakyThrows
+    public static Integer request(HttpModel httpModel, OutputStream outputStream, Map<String, Set<Object>> headers) throws IOException {
+        //构建超时参数
+        RequestConfig.Builder builder = RequestConfig.custom();
+        if (httpModel.getTimeOut() != null) {
+            builder.setSocketTimeout(httpModel.getTimeOut());
+        }
+        RequestConfig requestConfig = builder.build();
+
+        //忽略ssl
+        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
+            @Override
+            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+                return true;
+            }
+        }).build();
+        CloseableHttpClient httpclient = HttpClients.custom()
+                .setDefaultRequestConfig(requestConfig)
+                .setSSLContext(sslContext)
+                .setSSLHostnameVerifier(new NoopHostnameVerifier())
+                .build();
+
+//        CloseableHttpClient httpclient = HttpClients.createDefault();
+        HttpRequestBase requestBase = null;
+        String[] urls = httpModel.getUrl().split("://");
+
+        String url = urls[0] + "://" + UrlEncodeUtil.encode(urls[1]);
+
+        //请求类型的判断
+        if (httpModel.getMethod() == MethodType.Get || httpModel.getMethod() == null) {
+            requestBase = new HttpGet(url);
+        } else if (httpModel.getMethod() == MethodType.Post || httpModel.getMethod() == MethodType.Json) {
+            HttpPost httpPost = new HttpPost(url);
+            httpPost.setEntity(buildHttpEntity(httpModel));
+            requestBase = httpPost;
+        }
+
+        //设置请求头
+        if (httpModel.getHeader() != null) {
+            for (Map.Entry<String, Object> entry : httpModel.getHeader().entrySet()) {
+                requestBase.setHeader(entry.getKey(), String.valueOf(entry.getValue()));
+            }
+        }
+
+
+        //开始请求
+        CloseableHttpResponse response = httpclient.execute(requestBase);
+
+        if (headers != null) {
+            for (Header header : response.getAllHeaders()) {
+                Set<Object> val = headers.get(header.getName());
+                if (val == null) {
+                    val = new HashSet<>();
+                    headers.put(header.getName(), val);
+                }
+                val.add(header.getValue());
+            }
+        }
+
+        //转发数据流
+        @Cleanup InputStream inputStream = response.getEntity().getContent();
+        int size = StreamUtils.copy(inputStream, outputStream);
+        log.debug("requestUrl : " + httpModel.getUrl() + " , responseSize : " + size);
+        return response.getStatusLine().getStatusCode();
+    }
+
+
+    /**
+     * 获取body部分
+     *
+     * @param headers
+     * @param content
+     * @return
+     */
+    public static Object getBody(Map<String, Set<Object>> headers, byte[] content) {
+        Set<Object> contentTypeHeader = headers.get("Content-Type");
+
+
+        Object ret = null;
+
+        String contentType = null;
+        String charset = null;
+        if (contentTypeHeader != null && contentTypeHeader.size() > 0) {
+            String val = String.valueOf(contentTypeHeader.toArray(new Object[0])[0]);
+            String[] tmp = val.split(";");
+            if (tmp.length > 0) {
+                contentType = tmp[0];
+            }
+            if (tmp.length > 1) {
+                charset = tmp[1];
+            }
+        }
+
+        //获取字符编码
+        if (charset != null) {
+            String[] charsetArr = charset.split("=");
+            if (charset.length() > 0) {
+                charset = charsetArr[1];
+            }
+        }
+
+
+        try {
+            String contentStr = new String(content, charset == null ? "UTF-8" : charset);
+            if ("application/json".equals(contentType)) {
+                ret = JsonUtil.toObject(contentStr, Object.class);
+            } else {
+                ret = contentStr;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+
+        return ret;
+    }
+
+
+    /**
+     * 创建数据
+     *
+     * @param httpModel
+     * @return
+     */
+    private static StringEntity buildHttpEntity(HttpModel httpModel) {
+        String body = null;
+        String mimeType = null;
+        if (httpModel.getMethod() == MethodType.Post) {
+            mimeType = "application/x-www-form-urlencoded";
+            if (httpModel.getBody() == null) {
+                body = "";
+            } else if (httpModel.getBody() instanceof String) {
+                body = String.valueOf(httpModel.getBody());
+            } else {
+                //支持对象和map
+                StringBuffer sb = new StringBuffer();
+                Map<String, Object> bean = null;
+                if (httpModel.getBody() instanceof Map) {
+                    bean = (Map<String, Object>) httpModel.getBody();
+                } else {
+                    bean = BeanMap.create(body);
+                }
+                bean.entrySet().forEach((entry) -> {
+                    sb.append(UrlEncodeUtil.encode(entry.getKey()) + "=" + UrlEncodeUtil.encode(String.valueOf(entry.getValue())) + "&");
+                });
+                body = sb.toString();
+            }
+        } else if (httpModel.getMethod() == MethodType.Json) {
+            mimeType = "application/json";
+            body = httpModel.getBody() == null ? "{}" : JsonUtil.toJson(httpModel.getBody());
+        }
+        return new StringEntity(body, ContentType.create(mimeType, httpModel.getCharset()));
+    }
+
+
+    /**
+     * 创建post信息
+     *
+     * @param m
+     * @return
+     */
+    public static String buildPostInfo(Map<String, Object> m) {
+        final StringBuilder sb = new StringBuilder();
+        m.entrySet().forEach((it) -> {
+            Object val = it.getValue();
+            List<String> values;
+            if (val instanceof Collection) {
+                values = new ArrayList<String>((Collection<String>) val);
+            } else if (val.getClass().isArray()) {
+                values = Arrays.asList((String[]) val);
+            } else {
+                values = new ArrayList<String>() {{
+                    add(String.valueOf(it.getValue()));
+                }};
+            }
+            appendFormInfo(sb, it.getKey(), values);
+        });
+        return sb.toString();
+    }
+
+    /**
+     * 构建表单信息
+     *
+     * @param sb
+     * @param key
+     * @param values
+     */
+    private static void appendFormInfo(StringBuilder sb, String key, List<String> values) {
+        for (String value : values) {
+            sb.append(key + "=" + value + "&");
+        }
+    }
+
+
+}

+ 54 - 0
src/main/java/com/zswl/dataservice/utils/net/apache/HttpModel.java

@@ -0,0 +1,54 @@
+package com.zswl.dataservice.utils.net.apache;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.validation.annotation.Validated;
+
+import java.util.Map;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@Validated
+public class HttpModel {
+
+
+    /**
+     * Url地址
+     */
+    private String url;
+
+
+    /**
+     * 网络请求方式
+     */
+    private MethodType method;
+
+
+    /**
+     * 请求头
+     */
+    private Map<String, Object> header;
+
+
+    /**
+     * 请求体,仅为post生效
+     */
+    private Object body;
+
+
+    /**
+     * 请求编码
+     */
+    private String charset;
+
+
+    /**
+     * 超时
+     */
+    private Integer timeOut;
+
+}

+ 10 - 0
src/main/java/com/zswl/dataservice/utils/net/apache/MethodType.java

@@ -0,0 +1,10 @@
+package com.zswl.dataservice.utils.net.apache;
+
+/**
+ * 方法类型
+ */
+public enum MethodType {
+    Post,
+    Get,
+    Json
+}

+ 34 - 0
src/main/java/com/zswl/dataservice/utils/net/apache/ResponseModel.java

@@ -0,0 +1,34 @@
+package com.zswl.dataservice.utils.net.apache;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.util.Map;
+import java.util.Set;
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class ResponseModel {
+
+    /**
+     * 响应编码
+     */
+    private int code;
+
+
+    /**
+     * header
+     */
+    private Map<String, Set<Object>> headers;
+
+    /**
+     * body
+     */
+    private Object body;
+
+
+}

+ 48 - 0
src/main/java/com/zswl/dataservice/utils/net/apache/UrlEncodeUtil.java

@@ -0,0 +1,48 @@
+package com.zswl.dataservice.utils.net.apache;
+
+import lombok.SneakyThrows;
+
+import java.net.URLEncoder;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * URL编码工具
+ */
+public class UrlEncodeUtil {
+
+    private final static String[] NotEncodeCharset = new String[]{
+            ":", "/", "\\", "&", "?", "="
+    };
+    private final static Set<Integer> NotEncodeAscii = Collections.synchronizedSet(new HashSet<>());
+
+    static {
+        for (String s : NotEncodeCharset) {
+            try {
+                NotEncodeAscii.add((int) s.getBytes("UTF-8")[0]);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    @SneakyThrows
+    public static String encode(String url) {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < url.length(); i++) {
+            String str = url.substring(i, i + 1);
+            int ascii = (int) str.getBytes("UTF-8")[0];
+            // 0 - 9  , A - Z , a = z , ( NotEncodeCharset  )
+            if ((ascii >= 48 && ascii <= 57) || (ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122) || (NotEncodeAscii.contains(ascii))) {
+                sb.append(str);
+            } else {
+                sb.append(URLEncoder.encode(str, "UTF-8"));
+            }
+        }
+
+        return sb.toString();
+    }
+
+
+}

+ 3 - 0
src/main/resources/application-dev.yml

@@ -62,6 +62,9 @@ spring:
 artemis:
   alwaysSessionAsync: true
 
+fullcard:
+  url: http://192.168.0.104:9100
+
 # 阿里云OSS
 oss:
   maxCacheMinutes: 10