Browse Source

改为UrlConnection发送json

zhengqiang 5 năm trước cách đây
mục cha
commit
4aac56ef20

+ 4 - 5
common/src/main/java/com/jpsoft/smart/modules/common/utils/HttpConnectionUtil.java

@@ -32,8 +32,8 @@ import java.util.Iterator;
 import java.util.Map;
 
 public class HttpConnectionUtil {
-	private static int connectTimeoutMs = 5000;
-	private static int readTimeoutMs = 5000;
+	private static int connectTimeoutMs = 10000;
+	private static int readTimeoutMs = 10000;
 	private static String charSet = "UTF-8";
 
 	public static String getHttpContent(String url) {
@@ -234,7 +234,7 @@ public class HttpConnectionUtil {
     public static String requestByPost(String url,String charSet,String data, int connectTimeoutMs, int readTimeoutMs){
     	try{
 	        BasicHttpClientConnectionManager connManager;
-	        
+
 	        connManager = new BasicHttpClientConnectionManager(
 	                RegistryBuilder.<ConnectionSocketFactory>create()
 	                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
@@ -251,7 +251,6 @@ public class HttpConnectionUtil {
 	                .setConnectionManager(connManager)
 	                .build();
 
-
 	        HttpPost httpPost = new HttpPost(url);
 
 	        RequestConfig requestConfig = RequestConfig.custom()
@@ -260,7 +259,7 @@ public class HttpConnectionUtil {
 					.build();
 
 	        httpPost.setConfig(requestConfig);
-	
+
 	        StringEntity postEntity = new StringEntity(data, charSet);
 	        httpPost.addHeader("Content-Type", "text/xml");
 	        httpPost.setEntity(postEntity);

+ 76 - 0
common/src/main/java/com/jpsoft/smart/modules/common/utils/WechatMessageUtil.java

@@ -6,7 +6,12 @@ import lombok.extern.slf4j.Slf4j;
 import net.sf.json.JSONObject;
 import org.apache.commons.lang3.StringUtils;
 
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.math.BigDecimal;
+import java.net.HttpURLConnection;
+import java.net.URL;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.regex.Matcher;
@@ -342,6 +347,77 @@ public class WechatMessageUtil {
         return result;
     }
 
+    public static String sendNativeTemplate(String appId,String appSecret,String templateId, String openId,JSONObject sendData,String urlPath) {
+        String result = "";
+
+        try {
+            AccessToken accessToken = WeixinUtil.getAccessToken(appId, appSecret);
+
+            if (accessToken == null) {
+                throw new Exception("token无法获取");
+            }
+
+            //发送模版内容
+            String sendTemplateUrl = send_template.replace("ACCESS_TOKEN", accessToken.getToken());
+
+            JSONObject sendTemplateData = new JSONObject();
+
+            sendTemplateData.put("touser", openId);
+            sendTemplateData.put("template_id", templateId);
+            sendTemplateData.put("url", urlPath);
+            sendTemplateData.put("data", sendData);
+
+            URL url = new URL(sendTemplateUrl);
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            conn.setRequestMethod("POST");
+            conn.setDoOutput(true);
+            conn.setDoInput(true);
+            conn.setUseCaches(false);
+            conn.setRequestProperty("Connection", "Keep-Alive");
+            conn.setRequestProperty("Charset", "UTF-8");
+
+            // 设置文件类型:
+            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
+
+            // 设置接收类型否则返回415错误
+            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
+            conn.setRequestProperty("accept","application/json");
+            conn.setConnectTimeout(5000);
+            conn.setReadTimeout(5000);
+
+            String dataStr = sendTemplateData.toString();
+
+            // 往服务器里面发送数据
+            byte[] buffer = dataStr.getBytes("UTF-8");
+
+            // 设置文件长度
+            conn.setRequestProperty("Content-Length", String.valueOf(buffer.length));
+            OutputStream output = conn.getOutputStream();
+            output.write(buffer);
+            output.flush();
+            output.close();
+
+            if (conn.getResponseCode() == 200) {
+                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
+
+                StringBuilder sb = new StringBuilder();
+                String line = "";
+
+                while ((line = reader.readLine()) != null) {
+                    sb.append(line);
+                }
+
+                result = sb.toString();
+
+                reader.close();
+            }
+        } catch (Exception ex) {
+            log.error(ex.getMessage(),ex);
+        }
+
+        return result;
+    }
+
     public static String getContent(String content) {
         String finallyContent = content;
         String regex = "<p.*?>(.*?)</p>";

+ 0 - 13
common/src/main/java/com/jpsoft/smart/modules/common/utils/WeixinUtil.java

@@ -297,9 +297,6 @@ public class WeixinUtil {
 		button3.put("key","文章");
 		buttonArray.add(button3);
 
-
-
-
 		data.put("button", buttonArray);
 		data.put("action_name", "QR_LIMIT_STR_SCENE");
 
@@ -315,18 +312,8 @@ public class WeixinUtil {
 		//创建菜单
 		String result = HttpConnectionUtil.getHttpContentByPost(" https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token.getToken(), "utf-8", data.toString());
 
-
-
 		return result;
-
 	}
 
-	public static void main(String[] args){
-
-		//String result = createMenu("wx0b3c41a903053808","43557bd62f77b0c3d6670e991872f0e7");
-		System.out.println("//");
-	}
-
-
 
 }

+ 43 - 16
web/src/main/java/com/jpsoft/smart/schduled/UnmeasureTemperatureAlarmTask.java

@@ -7,12 +7,10 @@ import com.jpsoft.smart.modules.base.entity.*;
 import com.jpsoft.smart.modules.base.service.*;
 import com.jpsoft.smart.modules.business.entity.WorkAttendance;
 import com.jpsoft.smart.modules.business.service.WorkAttendanceService;
-import com.jpsoft.smart.modules.common.utils.JwtUtil;
-import com.jpsoft.smart.modules.common.utils.OSSUtil;
-import com.jpsoft.smart.modules.common.utils.POIUtils;
-import com.jpsoft.smart.modules.common.utils.WechatMessageUtil;
+import com.jpsoft.smart.modules.common.utils.*;
 import com.jpsoft.smart.modules.sys.entity.SysLog;
 import com.jpsoft.smart.modules.sys.service.SysLogService;
+import com.jpsoft.smart.modules.wechat.entity.AccessToken;
 import com.sun.corba.se.spi.orbutil.threadpool.Work;
 import io.jsonwebtoken.Jwts;
 import io.jsonwebtoken.security.Keys;
@@ -33,9 +31,10 @@ import org.springframework.scheduling.annotation.Async;
 import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Component;
 
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
+import java.io.*;
+import java.net.HttpURLConnection;
 import java.net.SocketAddress;
+import java.net.URL;
 import java.net.URLEncoder;
 import java.security.Key;
 import java.text.ParseException;
@@ -464,9 +463,9 @@ public class UnmeasureTemperatureAlarmTask {
                 sendData.put("keyword3", keyword3);
                 sendData.put("remark", remark);
 
-                writeDbLog(String.format("向未测温人:%s 发送测温提醒通知",personInfo.getName()),alarmConfig.getCompanyId());
+                writeDbLog(String.format("向未测温人:%s,%s发送测温提醒通知",personInfo.getName(),personInfo.getOpenId()),alarmConfig.getCompanyId());
 
-                WechatMessageUtil.sendTemplate(sendData, wxConfig.getAppId(),wxConfig.getAppSecret(),remindTmplCode,personInfo.getOpenId(), null);
+                WechatMessageUtil.sendNativeTemplate(wxConfig.getAppId(),wxConfig.getAppSecret(),remindTmplCode,personInfo.getOpenId(),sendData,null);
             }
         }
     }
@@ -638,13 +637,41 @@ public class UnmeasureTemperatureAlarmTask {
     }
 
     public static void main(String[] args) {
-        String str = String.format(
-                "查询考勤时段:%s~%s,未考勤人员数量:%s",
-                "2020-04-24 08:00",
-                "2020-04-24 09:00",
-                10
-        );
-
-        System.out.println(str);
+        String message ="请抓紧时间在单位内任意打卡点打卡和测温!";
+
+        JSONObject sendData = new JSONObject();
+
+        JSONObject first = new JSONObject();
+        first.put("value", "未测温提醒");
+        first.put("color", "#FF0000");
+
+        JSONObject keyword1 = new JSONObject();
+        keyword1.put("value", "当前用户");
+        keyword1.put("color", "#173177");
+
+        JSONObject keyword2 = new JSONObject();
+        keyword2.put("value", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
+        keyword2.put("color", "#173177");
+
+        JSONObject keyword3 = new JSONObject();
+        keyword3.put("value", "待测温");
+        keyword3.put("color", "#173177");
+
+        JSONObject remark = new JSONObject();
+        remark.put("value", message);
+        remark.put("color", "#173177");
+
+        sendData.put("first", first);
+        sendData.put("keyword1", keyword1);
+        sendData.put("keyword2", keyword2);
+        sendData.put("keyword3", keyword3);
+        sendData.put("remark", remark);
+
+        String appId = "wx0b3c41a903053808";
+        String appSecret = "43557bd62f77b0c3d6670e991872f0e7";
+        String remindTmplCode = "Nsn_8-M25Ef_KThmin8uDocXeh8XVQMC1rVzBAIaeig";
+        String openId = "oLowyuB1PliW0qAnJJ56axydeUOM";
+
+        WechatMessageUtil.sendNativeTemplate(appId,appSecret,remindTmplCode,openId,sendData ,null);
     }
 }