1,微信基础配置WxContanst.java:
1 package com.pgo.modules.inv.subscribe;
2
3 public class WxContanst {
4
5 private static String APPID = "微信公众平台查看APPID";
6
7 private static String SECRET = "微信公众平台查看SECRET";
8
9 //用于测试,后期可维护到数据库中,公众平台配置
10 public static String TEMPLATE_ID_ = "z8eVgH_fEY-s-IE57-jbB0uYySJMb2hysm1yR2zPH0w";
11
12
13 // 微信小程序获取tokenURL
14 public static String TOKEN_URL_ = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
15 + WxContanst.APPID + "&secret=" + WxContanst.SECRET;
16
17 // 获取小程序openid的url
18 public static String URL(String js_code) {
19 return "https://api.weixin.qq.com/sns/jscode2session?appid=" + WxContanst.APPID + "&secret=" + WxContanst.SECRET
20 + "&js_code=" + js_code + "&grant_type=authorization_code";
21 }
22
23 /**
24 * 获取消息订阅的Url
25 * @param accessToken接口认证
26 * @return 消息订阅的Url
27 */
28 public static String subscribeUrl(String accessToken){
29 return "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken ;
30 }
31
32 }
2,http请求工具HttpSendUtils.java:
1 package com.pgo.modules.inv.subscribe;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.net.URI;
7 import java.util.ArrayList;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Map;
11
12 import org.apache.http.HttpEntity;
13 import org.apache.http.HttpResponse;
14 import org.apache.http.HttpStatus;
15 import org.apache.http.NameValuePair;
16 import org.apache.http.StatusLine;
17 import org.apache.http.client.HttpClient;
18 import org.apache.http.client.entity.UrlEncodedFormEntity;
19 import org.apache.http.client.methods.CloseableHttpResponse;
20 import org.apache.http.client.methods.HttpGet;
21 import org.apache.http.client.methods.HttpPost;
22 import org.apache.http.entity.StringEntity;
23 import org.apache.http.impl.client.CloseableHttpClient;
24 import org.apache.http.impl.client.DefaultHttpClient;
25 import org.apache.http.impl.client.HttpClients;
26 import org.apache.http.message.BasicNameValuePair;
27 import org.apache.http.protocol.HTTP;
28 import org.apache.http.util.EntityUtils;
29 import org.hibernate.internal.util.StringHelper;
30 import org.testng.log4testng.Logger;
31
32 @SuppressWarnings("deprecation")
33 public class HttpSendUtils {
34 private static Logger logger = Logger.getLogger(HttpSendUtils.class);
35
36 /**
37 * get请求
38 *
39 * @return
40 */
41 public static String doGet(String url) {
42 try {
43 HttpClient client = new DefaultHttpClient();
44 // 发送get请求
45 HttpGet request = new HttpGet(url);
46 HttpResponse response = client.execute(request);
47
48 /** 请求发送成功,并得到响应 **/
49 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
50 /** 读取服务器返回过来的json字符串数据 **/
51 String strResult = EntityUtils.toString(response.getEntity());
52
53 return strResult;
54 }
55 } catch (IOException e) {
56 e.printStackTrace();
57 }
58
59 return null;
60 }
61
62 /**
63 * post请求(用于key-value格式的参数)
64 *
65 * @param url
66 * @param params
67 * @return
68 */
69 public static String doPost(String url, Map params) {
70
71 BufferedReader in = null;
72 try {
73 // 定义HttpClient
74 HttpClient client = new DefaultHttpClient();
75 // 实例化HTTP方法
76 HttpPost request = new HttpPost();
77 request.setURI(new URI(url));
78
79 // 设置参数
80 List<NameValuePair> nvps = new ArrayList<NameValuePair>();
81 for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
82 String name = (String) iter.next();
83 String value = String.valueOf(params.get(name));
84 nvps.add(new BasicNameValuePair(name, value));
85
86 // System.out.println(name +"-"+value);
87 }
88 request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
89
90 HttpResponse response = client.execute(request);
91 int code = response.getStatusLine().getStatusCode();
92 if (code == 200) { // 请求成功
93 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
94 StringBuffer sb = new StringBuffer("");
95 String line = "";
96 String NL = System.getProperty("line.separator");
97 while ((line = in.readLine()) != null) {
98 sb.append(line + NL);
99 }
100
101 in.close();
102
103 return sb.toString();
104 } else { //
105 System.out.println("状态码:" + code);
106 return null;
107 }
108 } catch (Exception e) {
109 e.printStackTrace();
110
111 return null;
112 }
113 }
114
115 /**
116 * post请求(用于请求json格式的参数)
117 *
118 * @param url
119 * @param params
120 * @return
121 */
122 public static String doPost(String url, String params) throws Exception {
123 System.out.println("==============="+params+"=====================");
124 CloseableHttpClient httpclient = HttpClients.createDefault();
125 HttpPost httpPost = new HttpPost(url);// 创建httpPost
126 httpPost.setHeader("Accept", "application/json");
127 httpPost.setHeader("Content-Type", "application/json");
128 String charSet = "UTF-8";
129 if(StringHelper.isNotEmpty(params)){
130 StringEntity entity = new StringEntity(params, charSet);
131 httpPost.setEntity(entity);
132 }
133 CloseableHttpResponse response = null;
134
135 try {
136
137 response = httpclient.execute(httpPost);
138 StatusLine status = response.getStatusLine();
139 int state = status.getStatusCode();
140 if (state == HttpStatus.SC_OK) {
141 HttpEntity responseEntity = response.getEntity();
142 String jsonString = EntityUtils.toString(responseEntity);
143 return jsonString;
144 } else {
145 //logger.error("请求返回:" + state + "(" + url + ")");
146 }
147 } finally {
148 if (response != null) {
149 try {
150 response.close();
151 } catch (IOException e) {
152 e.printStackTrace();
153 }
154 }
155 try {
156 httpclient.close();
157 } catch (IOException e) {
158 e.printStackTrace();
159 }
160 }
161 return null;
162 }
163 }
3,微信操作工具类WxUtils.java:
1 package com.pgo.modules.inv.subscribe;
2
3 import java.util.Map;
4
5 import com.google.gson.Gson;
6 import com.pgo.modules.doradoframework.base.BaseBO;
7
8 public class WxUtils extends BaseBO {
9 /**
10 * 获取微信openId
11 *
12 * @param param
13 * @return
14 * @throws Exception
15 */
16 @SuppressWarnings("unchecked")
17 public static String getOpenIdByCode(String code, String param) throws Exception {
18 String openid = HttpSendUtils.doPost(WxContanst.URL(code), param);
19 Gson gson = new Gson();
20 Map<String, Object> res = gson.fromJson(openid, Map.class);
21 return (String) res.get("openid");
22 }
23
24 /**
25 * 获取微信access_token_
26 *
27 * @param param
28 * @return
29 * @throws Exception
30 */
31 @SuppressWarnings("unchecked")
32 public static String getAccessToken(String param) throws Exception {
33 String token = HttpSendUtils.doPost(WxContanst.TOKEN_URL_, param);
34 Gson gson = new Gson();
35 Map<String, Object> res = gson.fromJson(token, Map.class);
36 return (String) res.get("access_token");
37 }
38
39 // 通过关联的用户表查找openId
40 public static String getOpenIdByUserId(String userId) throws Exception {
41 // 此处为模拟测试,后期通过登录后保存的code直接使用
42 String code = "";
43 return WxUtils.getOpenIdByCode(code, null);
44 }
45
46 /**
47 * 获取订阅消息的Url
48 * @return url
49 * @throws Exception
50 */
51 public static String getSubUrl() throws Exception{
52 return WxContanst.subscribeUrl(WxUtils.getAccessToken(null));
53 }
54 /**
55 * 受框架影响openId可以直接从后台获取
56 * @param userId 用户的id
57 * @return openId
58 * @throws Exception
59 */
60 public static String getOpenIdDub1(String userId) throws Exception {
61
62 return null;
63 }
64
65 }
4,微信模板操作工具类WxSubscribeMessageUtils.java
1 package com.pgo.modules.inv.subscribe;
2
3 import java.util.HashMap;
4 import java.util.List;
5 import java.util.Map;
6 import java.util.Map.Entry;
7
8 import com.alibaba.fastjson.JSONObject;
9 import com.pgo.modules.common.du.domain.Tbdub1;
10 import com.pgo.modules.core.support.Result;
11 /**
12 * 通用订阅模板发送处理类
13 * @author baolu
14 *
15 */
16 public class WxSubscribeMessageUtils {
17
18 /**
19 * 消息模板通用设置
20 * @param parameter 模板参数
21 * @param template_id 模板ID
22 * @param userId 用户ID
23 * @param pageIndex 消息跳转的画面
24 * @return 发送结果
25 * @throws Exception
26 * 注:获取用户的openId可以灵活获取。
27 * 1,通过调用WxUtils.getOpenIdByUserId(userId),但是需要数据库存储openID和userId;
28 * 2,通过前端code调用getOpenIdByCode(code , paramer)获取openId
29 */
30 public static Result sendMessage(String toUserOpenId , Map<String , Object> parameter , String template_id , String userId , String pageIndex) throws Exception{
31 JSONObject templateData = new JSONObject();
32 //设置用户的openId,此处受到框架后台处理,可直接取openid,
33 //所以WxUtils.getOpenIdByUserId(null)暂时弃用
34 //WxUtils.getOpenIdByUserId(null);
35 //测试发送给管理员的消息
36 templateData.put("touser", toUserOpenId);
37 //设置订阅消息模板ID
38 templateData.put("template_id", template_id);
39 //设置点击消息跳转路径
40 templateData.put("page", pageIndex);
41 //设置消息内容
42 JSONObject data = new JSONObject();
43 for(Entry<String, Object> vo : parameter.entrySet()){
44 Map<String , Object> value = new HashMap<String , Object>();
45 value.put("value", vo.getValue());
46 data.put(vo.getKey() , value);
47 }
48 templateData.put("data", data);
49 //发送订阅消息的请求
50 String resMessage = HttpSendUtils.doPost(WxUtils.getSubUrl() , templateData.toString());
51 Result res = new Result("1" , resMessage);
52 return res;
53 }
54 }
5,测试代码:
package com.pgo.modules.inv.subscribe;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.pgo.modules.core.support.Result;
/**
* 订阅消息模板发送
* @author baolu
*
*/
public class SubscribeMessage {
//测试消息发送是否成功
public static void main(String[] arg) throws Exception{
Map<String , Object> mp = new HashMap<String , Object>();
mp.put("name1", "通知");
mp.put("date2", "2013-01-01");
mp.put("time3", "16:28:00");
Result sendMessage = WxSubscribeMessageUtils.sendMessage("oglgM5Pi2MF8KbC6_PhCtFw6o2HI" , mp, WxContanst.TEMPLATE_ID_, "admin", "pages/login/login");
System.out.println(sendMessage.getMessage());
}
}
注意:access_token_有时间限制和请求次数限制,可以存放在redis或者内存中,这里没有做处理,请参考微信小程序开发手册
我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当
我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI
这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD
我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=
我正在使用Ruby,我正在与一个网络端点通信,该端点在发送消息本身之前需要格式化“header”。header中的第一个字段必须是消息长度,它被定义为网络字节顺序中的2二进制字节消息长度。比如我的消息长度是1024。如何将1024表示为二进制双字节? 最佳答案 Ruby(以及Perl和Python等)中字节整理的标准工具是pack和unpack。ruby的packisinArray.您的长度应该是两个字节长,并且按网络字节顺序排列,这听起来像是n格式说明符的工作:n|Integer|16-bitunsigned,network(bi
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt