在上一篇文章中我们完成本地的内网穿透开发已经测试公众号的对接。接下来我们将讲述如何开发。
第一步:添加post的接口,如下:
@RequestMapping(value = "wx", method = RequestMethod.POST)
// post 方法用于接收微信服务端消息
public void DoPost(HttpServletRequest request,HttpServletResponse response) {
System.out.println("这是 post 方法!");
try{
Map<String, String> map=MessageUtil.parseXml(request);
System.out.println("============================="+map.get("Content"));
String msgtype=map.get("MsgType");
if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)){
String infos=EventDispatcher.processEvent(map); //进入事件处理
response.getWriter().print(infos);
}else{
String info=MsgDispatcher.processMessage(map); //进入消息处理
response.getWriter().print(info);
}
}catch(Exception e){
//logger.error(e,e);
}
}
红色处请注意,这是因为我们需要把用户发的信息收到,并且准备好返回结果,返回给客户,所以需要response回去。
第二步:区分他是事件还是消息在第一步中已经处理好了。
接下来有两个方法:
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.practice.wx.util.GetUseInfo;
import com.practice.wx.util.MessageUtil;
import com.practice.wx.vo.Article;
import com.practice.wx.vo.NewsMessage;
/**
* ClassName: EventDispatcher
* @Description: 事件消息业务分发器
* @author dapengniao
* @date 2016 年 3 月 7 日 下午 4:04:41
*/
public class EventDispatcher {
public static String processEvent(Map<String, String> map) {
String openid=map.get("FromUserName"); //用户 openid
String mpid=map.get("ToUserName"); //公众号原始 ID
/*GetUseInfo userInfo=new GetUseInfo();
Map<String,String> maps=userInfo.Openid_userinfo(map.get("FromUserName"));*/
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { //关注事件
System.out.println("==============这是关注事件!");
try {
//对图文消息
NewsMessage newmsg=new NewsMessage();
newmsg.setToUserName(openid);
newmsg.setFromUserName(mpid);
newmsg.setCreateTime(new Date().getTime());
newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // 关注事件
System.out.println("==============这是关注事件!");
try {
HashMap<String, String> userinfo=GetUseInfo.Openid_userinfo(openid);
Article article=new Article();
article.setDescription("欢迎来到赵红明的个人博客:菜鸟程序员成长之路!"); //图文消息的描述
article.setPicUrl(userinfo.get("headimgurl")); //图文消息图片地址
article.setTitle("尊敬的:"+userinfo.get("nickname")+",你好!"); //图文消息标题
article.setUrl("https://avatar.csdn.net/2/9/7/1_wszhm123.jpg?1523158456"); //图文 url 链接
List<Article> list=new ArrayList<Article>();
list.add(article); //这里发送的是单图文,如果需要发送多图文则在这里 list 中加入多个 Article 即可!
newmsg.setArticleCount(list.size());
newmsg.setArticles(list);
return MessageUtil.newsMessageToXml(newmsg);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("====代码有问题额☺!");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) { //取消关注事件
System.out.println("==============这是取消关注事件!");
}
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SCAN)) { //扫描二维码事件
System.out.println("==============这是扫描二维码事件!");
}
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_LOCATION)) { //位置上报事件
System.out.println("==============这是位置上报事件!");
}
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_CLICK)) { //自定义菜单点击事件
System.out.println("==============这是自定义菜单点击事件!");
}
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_VIEW)) { //自定义菜单 View 事件
System.out.println("==============这是自定义菜单 View 事件!");
}
return null;
}
}
还有一个java,如下:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.practice.wx.util.MessageUtil;
import com.practice.wx.vo.Article;
import com.practice.wx.vo.NewsMessage;
import com.practice.wx.vo.TextMessage;
/**
* ClassName: MsgDispatcher
* @Description: 消息业务处理分发器
* @author dapengniao
* @date 2016 年 3 月 7 日 下午 4:04:21
*/
public class MsgDispatcher {
public static String processMessage(Map<String, String> map) {
String openid=map.get("FromUserName"); //用户 openid
String mpid=map.get("ToUserName"); //公众号原始 ID
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) { // 文本消息
//普通文本消息
TextMessage txtmsg=new TextMessage();
txtmsg.setToUserName(openid);
txtmsg.setFromUserName(mpid);
txtmsg.setCreateTime(new Date().getTime());
txtmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) { // 文本消息
String content=map.get("Content");
if("1".equals(content)){
txtmsg.setContent("你好,你发送的内容是 1!");
}else if("2".equals(content)){
txtmsg.setContent("你好,你发送的内容是 2!");
}else if("3".equals(content)){
txtmsg.setContent("你好,你发送的内容是 3!");
}else if("4".equals(content)){
txtmsg.setContent("<a href=\"https://blog.csdn.net/wszhm123\">赵红明博客</a>");
}else{
txtmsg.setContent("你好,欢迎来到赵红明博客!");
}
String info=MessageUtil.textMessageToXml(txtmsg);
System.out.println(info);
return info;
}
}
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) { // 图片消息
System.out.println("==============这是图片消息!");
//对图文消息
NewsMessage newmsg=new NewsMessage();
newmsg.setToUserName(openid);
newmsg.setFromUserName(mpid);
newmsg.setCreateTime(new Date().getTime());
newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) { // 图片消息
System.out.println("==============这是图片消息!");
Article article=new Article();
article.setDescription("这是图文消息 1"); //图文消息的描述
article.setPicUrl("http://res.cuiyongzhi.com/2016/03/201603086749_6850.png"); //图文消息图片地址
article.setTitle("图文消息 1"); //图文消息标题
article.setUrl("https://blog.csdn.net/wszhm123"); //图文 url 链接
List<Article> list=new ArrayList<Article>();
list.add(article); //这里发送的是单图文,如果需要发送多图文则在这里 list 中加入多个 Article 即可!
newmsg.setArticleCount(list.size());
newmsg.setArticles(list);
String info=MessageUtil.newsMessageToXml(newmsg);
System.out.println(info);
return info;
}
}
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) { // 链接消息
System.out.println("==============这是链接消息!");
}
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) { // 位置消息
System.out.println("==============这是位置消息!");
}
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) { // 视频消息
System.out.println("==============这是视频消息!");
}
if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) { // 语音消息
System.out.println("==============这是语音消息!");
}
return null;
}
}
这样就出来好处理什么样的信息。
第三步:准备相应的util.:
在准备相应的公用的util的时候,需要一定的jar包,如下:
<!-- xml -->
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.dom4j.dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.8</version>
</dependency>
<!-- https -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
(1):在微信公众号开发的时候,公用的收发信息接口HttpUtils。如下:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* ClassName: HttpUtils
*
* @Description: http 请求工具类
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 3:57:14
*/
@SuppressWarnings("deprecation")
public class HttpUtils {
/**
* @Description: http get 请求共用方法
* @param @param reqUrl
* @param @param params
* @param @return
* @param @throws Exception
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 3:57:39
*/
@SuppressWarnings("resource")
public static String sendGet(String reqUrl, Map<String, String> params)
throws Exception {
InputStream inputStream = null;
HttpGet request = new HttpGet();
try {
String url = buildUrl(reqUrl, params);
System.out.println(url);
HttpClient client = new DefaultHttpClient();
request.setHeader("Accept-Encoding", "gzip");
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
inputStream = response.getEntity().getContent();
String result = getJsonStringFromGZIP(inputStream);
return result;
} finally {
if (inputStream != null) {
inputStream.close();
}
request.releaseConnection();
}
}
/**
* @Description: http post 请求共用方法
* @param @param reqUrl
* @param @param params
* @param @return
* @param @throws Exception
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 3:57:53
*/
@SuppressWarnings("resource")
public static String sendPost(String reqUrl, Map<String, String> params)
throws Exception {
try {
Set<String> set = params.keySet();
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : set) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
if (list.size() > 0) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(reqUrl);
request.setHeader("Accept-Encoding", "gzip");
request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
HttpResponse response = client.execute(request);
InputStream inputStream = response.getEntity().getContent();
try {
String result = getJsonStringFromGZIP(inputStream);
return result;
} finally {
inputStream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("网络连接失败,请连接网络后再试");
}
} else {
throw new Exception("参数不全,请稍后重试");
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("发送未知异常");
}
}
/**
* @Description: http post 请求 json 数据
* @param @param urls
* @param @param params
* @param @return
* @param @throws ClientProtocolException
* @param @throws IOException
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 3:58:15
*/
public static String sendPostBuffer(String urls, String params)
throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(urls);
StringEntity se = new StringEntity(params, HTTP.UTF_8);
request.setEntity(se);
// 发送请求
@SuppressWarnings("resource")
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
// 得到应答的字符串,这也是一个 JSON 格式保存的数据
String retSrc = EntityUtils.toString(httpResponse.getEntity());
request.releaseConnection();
return retSrc;
}
/**
* @Description: http 请求发送 xml 内容
* @param @param urlStr
* @param @param xmlInfo
* @param @return
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 3:58:32
*/
public static String sendXmlPost(String urlStr, String xmlInfo) {
// xmlInfo xml 具体字符串
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter out = new OutputStreamWriter(
con.getOutputStream());
out.write(new String(xmlInfo.getBytes("utf-8")));
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String lines = "";
for (String line = br.readLine(); line != null; line = br
.readLine()) {
lines = lines + line;
}
return lines; // 返回请求结果
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
private static String getJsonStringFromGZIP(InputStream is) {
String jsonString = null;
try {
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(2);
// 取前两个字节
byte[] header = new byte[2];
int result = bis.read(header);
// reset 输入流到开始位置
bis.reset();
// 判断是否是 GZIP 格式
int headerData = getShort(header);
// Gzip 流 的前两个字节是 0x1f8b
if (result != -1 && headerData == 0x1f8b) {
// LogUtil.i("HttpTask", " use GZIPInputStream ");
is = new GZIPInputStream(bis);
} else {
// LogUtil.d("HttpTask", " not use GZIPInputStream");
is = bis;
}
InputStreamReader reader = new InputStreamReader(is, "utf-8");
char[] data = new char[100];
int readSize;
StringBuffer sb = new StringBuffer();
while ((readSize = reader.read(data)) > 0) {
sb.append(data, 0, readSize);
}
jsonString = sb.toString();
bis.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}
private static int getShort(byte[] data) {
return (data[0] << 8) | data[1] & 0xFF;
}
/**
* 构建 get 方式的 url
*
* @param reqUrl
* 基础的 url 地址
* @param params
* 查询参数
* @return 构建好的 url
*/
public static String buildUrl(String reqUrl, Map<String, String> params) {
StringBuilder query = new StringBuilder();
Set<String> set = params.keySet();
for (String key : set) {
query.append(String.format("%s=%s&", key, params.get(key)));
}
return reqUrl + "?" + query.toString();
}
}
(2):消息工具类MessageUtil 。如下:
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.practice.wx.vo.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
* ClassName: MessageUtil
* @Description: 消息工具类
* @author dapengniao
* @date 2016 年 3 月 7 日 上午 10:05:04
*/
public class MessageUtil {
/**
* 返回消息类型:文本
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 返回消息类型:音乐
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 返回消息类型:图文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";
/**
* 返回消息类型:图片
*/
public static final String RESP_MESSAGE_TYPE_Image = "image";
/**
* 返回消息类型:语音
*/
public static final String RESP_MESSAGE_TYPE_Voice = "voice";
/**
* 返回消息类型:视频
*/
public static final String RESP_MESSAGE_TYPE_Video = "video";
/**
* 请求消息类型:文本
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 请求消息类型:图片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 请求消息类型:链接
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 请求消息类型:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
/**
* 请求消息类型:音频
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 请求消息类型:视频
*/
public static final String REQ_MESSAGE_TYPE_VIDEO = "video";
/**
* 请求消息类型:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 事件类型:subscribe(订阅)
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 事件类型:unsubscribe(取消订阅)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 事件类型:CLICK(自定义菜单点击事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/**
* 事件类型:VIEW(自定义菜单 URl 视图)
*/
public static final String EVENT_TYPE_VIEW = "VIEW";
/**
* 事件类型:LOCATION(上报地理位置事件)
*/
public static final String EVENT_TYPE_LOCATION = "LOCATION";
/**
* 事件类型:LOCATION(上报地理位置事件)
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
/**
* @Description: 解析微信发来的请求(XML)
* @param @param request
* @param @return
* @param @throws Exception
* @author dapengniao
* @date 2016 年 3 月 7 日 上午 10:04:02
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
// 将解析结果存储在 HashMap 中
Map<String, String> map = new HashMap<String, String>();
// 从 request 中取得输入流
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到 xml 根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList)
map.put(e.getName(), e.getText());
// 释放资源
inputStream.close();
inputStream = null;
return map;
}
/**
* @Description: 文本消息对象转换成 xml
* @param @param textMessage
* @param @return
* @author dapengniao
* @date 2016 年 3 月 8 日 下午 4:13:22
*/
public static String textMessageToXml(TextMessage textMessage) {
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* @Description: 图文消息对象转换成 xml
* @param @param newsMessage
* @param @return
* @author dapengniao
* @date 2016 年 3 月 8 日 下午 4:14:09
*/
public static String newsMessageToXml(NewsMessage newsMessage) {
xstream.alias("xml", newsMessage.getClass());
xstream.alias("item", new Article().getClass());
return xstream.toXML(newsMessage);
}
/**
* @Description: 图片消息对象转换成 xml
* @param @param imageMessage
* @param @return
* @author dapengniao
* @date 2016 年 3 月 9 日 上午 9:25:51
*/
public static String imageMessageToXml(ImageMessage imageMessage) {
xstream.alias("xml", imageMessage.getClass());
return xstream.toXML(imageMessage);
}
/**
* @Description: 语音消息对象转换成 xml
* @param @param voiceMessage
* @param @return
* @author dapengniao
* @date 2016 年 3 月 9 日 上午 9:27:26
*/
public static String voiceMessageToXml(VoiceMessage voiceMessage) {
xstream.alias("xml", voiceMessage.getClass());
return xstream.toXML(voiceMessage);
}
/**
* @Description: 视频消息对象转换成 xml
* @param @param videoMessage
* @param @return
* @author dapengniao
* @date 2016 年 3 月 9 日 上午 9:31:09
*/
public static String videoMessageToXml(VideoMessage videoMessage) {
xstream.alias("xml", videoMessage.getClass());
return xstream.toXML(videoMessage);
}
/**
* @Description: 音乐消息对象转换成 xml
* @param @param musicMessage
* @param @return
* @author dapengniao
* @date 2016 年 3 月 8 日 下午 4:13:36
*/
public static String musicMessageToXml(MusicMessage musicMessage) {
xstream.alias("xml", musicMessage.getClass());
return xstream.toXML(musicMessage);
}
@SuppressWarnings("unused")
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有 xml 节点的转换都增加 CDATA 标记
boolean cdata = true;
@SuppressWarnings("rawtypes")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
}
通过上面两个方法就解决了,处理接收和发送给公众号信息的问题。
第四步:准备相应的微信公众号基类;
java微信公众号开发涉及到的类
第五步:当我们启动程序的时候就需要相应的知道access_token,因为access_token是72000秒重新获取一次,所以需要准备定时任务,本处用的是springBoot的定时任务。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.practice.wx.service.GlobalConstants;
import com.practice.wx.service.InterfaceUrlInti;
import com.practice.wx.util.HttpUtils;
import net.sf.json.JSONObject;
/**
* ClassName: WeChatTask
* @Description: 微信两小时定时任务体
* @date 2016 年 3 月 10 日 下午 1:42:29
*/
@Component
public class WeChatTask {
/**
* @Description: 任务执行体
* @param @throws Exception
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 2:04:37
*/
@Scheduled(fixedRate = 7200000)
public void getToken_getTicket() throws Exception {
InterfaceUrlInti.init();
getToken();
}
public void getToken() throws Exception{
System.out.println("---定時任務凱斯--");
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "client_credential");
params.put("appid", GlobalConstants.getInterfaceUrl("appid"));
params.put("secret", GlobalConstants.getInterfaceUrl("secret"));
String jstoken = HttpUtils.sendGet(
GlobalConstants.getInterfaceUrl("tokenUrl"), params);
String access_token = JSONObject.fromObject(jstoken).getString(
"access_token"); // 获取到 token 并赋值保存
GlobalConstants.interfaceUrlProperties.put("access_token", access_token);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"token 为=============================="+access_token);
}
}
其中涉及到appId和secret这两个是微信公众号提供的,配置到文件里。所以需要相应的配置文件。
(1):一个是相应url的interface_url.properties
##获取access_token
tokenUrl=https\://api.weixin.qq.com/cgi-bin/token
##获取用户信息
OpenidUserinfoUrl=https\://api.weixin.qq.com/cgi-bin/user/info
(2):一个是微信公众号基本信息wechat.properties
#微信公众号的 appid
appid=wx0023ddd7e2be7368
#微信公众号的secret
secret=71ad55dde689b6c0691f5a76233740a7
当然我们有了配置文件需要读取,这样才能搞定,其中读取配置文件的java如下:
import java.util.Properties;
import org.springframework.stereotype.Component;
/**
* ClassName: GlobalConstants
* @Description: 获取配置文件数据
* @author XiaoJiu
* @date 2017-10-19
*/
@Component
public class GlobalConstants {
public static Properties interfaceUrlProperties;
public static String getInterfaceUrl(String key) {
return (String) interfaceUrlProperties.get(key);
}
}
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
/**
* ClassName: InterfaceUrlInti
* @Description: 项目启动初始化方法
* @author dapengniao
* @date 2016 年 3 月 10 日 下午 4:08:21
*/
@Component
public class InterfaceUrlInti {
private static Logger logger = Logger.getLogger(InterfaceUrlInti.class);
public synchronized static void init(){
logger.info("InterfaceUrlInti->init start");
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
if(GlobalConstants.interfaceUrlProperties==null){
GlobalConstants.interfaceUrlProperties = new Properties();
}
InputStream in = null;
try {
in = cl.getResourceAsStream("config/interface_url.properties");
props.load(in);
for(Object key : props.keySet()){
GlobalConstants.interfaceUrlProperties.put(key, props.get(key));
}
props = new Properties();
in = cl.getResourceAsStream("config/wechat.properties");
props.load(in);
for(Object key : props.keySet()){
GlobalConstants.interfaceUrlProperties.put(key, props.get(key));
}
logger.info("InterfaceUrlInti->init end");
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
}
这样相应的微信公众号基本开发功能就OK了。