admin 管理员组

文章数量: 1184232


2024年3月29日发(作者:异步fifo主要验什么)

微信公众平台的Java开发详解(工程代码+解析)

说明:

本次的教程主要是对微信公众平台开发者模式的讲解,网络上很多类似文章,但很多

都让初学微信开发的人一头雾水,所以总结自己的微信开发经验,将微信开发的整个过程

系统的列出,并对主要代码进行讲解分析,让初学者尽快上手。

在阅读本文之前,应对微信公众平台的官方开发文档有所了解,知道接收和发送的都

是xml格式的数据。另外,在做内容回复时用到了

图灵机器人的api接口

,这是一个自

然语言解析的开放平台,可以帮我们解决整个微信开发过程中最困难的问题,此处不多

讲,下面会有其详细的调用方式。

1.1 在登录微信官方平台之后,开启开发者模式,此时需要我们填写url和

token,所谓url就是我们自己服务器的接口,用来实

现,相关解释已经在注释中说明,代码如下:

[java] view plaincopy

1. package t;

2. import edReader;

3. import ption;

4. import tream;

5. import treamReader;

6. import Stream;

7. import tException;

8. import rvlet;

9. import rvletRequest;

10. import rvletResponse;

11. import Process;

12. /**

13. * 微信服务端收发消息接口

14. *

15. * @author pamchen-1

16. *

17. */

18. public class WechatServlet extends HttpServlet {

19. /**

20. * The doGet method of the servlet.

21. *

22. * This method is called when a form has its tag value method equals to

get.

23. *

24. * @param request

25. * the request send by the client to the server

26. * @param response

27. * the response send by the server to the client

28. * @throws ServletException

29. * if an error occurred

30. * @throws IOException

31. * if an error occurred

32. */

33. public void doGet(HttpServletRequest request, HttpServletResponse re

sponse)

34. throws ServletException, IOException {

35. racterEncoding("UTF-8");

36. racterEncoding("UTF-8");

37. /** 读取接收到的xml消息 */

38. StringBuffer sb = new StringBuffer();

39. InputStream is = utStream();

40. InputStreamReader isr = new InputStreamReader(is, "UTF-8");

41. BufferedReader br = new BufferedReader(isr);

42. String s = "";

43. while ((s = ne()) != null) {

44. (s);

45. }

46. String xml = ng(); //次即为接收到微信端发送过来的xml数据

47. String result = "";

48. /** 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr

参数,此时需要把它直接返回 */

49. String echostr = ameter("echostr");

50. if (echostr != null && () > 1) {

51. result = echostr;

52. } else {

53. //正常的微信处理流程

54. result = new WechatProcess().processWechatMag(xml);

55. }

56. try {

57. OutputStream os = putStream();

58. (es("UTF-8"));

59. ();

60. ();

61. } catch (Exception e) {

62. tackTrace();

63. }

64. }

65. /**

66. * The doPost method of the servlet.

67. *

68. * This method is called when a form has its tag value method equals to

69. * post.

70. *

71. * @param request

72. * the request send by the client to the server

73. * @param response

74. * the response send by the server to the client

75. * @throws ServletException

76. * if an error occurred

77. * @throws IOException

78. * if an error occurred

79. */

80. public void doPost(HttpServletRequest request, HttpServletResponse r

esponse)

81. throws ServletException, IOException {

82. doGet(request, response);

83. }

84. }

1.2 相应的配置信息如下,在生成的同时,可

自动生成中的配置。前面所提到的url处可以填写例如:

http;//服务器地址/项目名/

[html] view plaincopy

1.

2.

3. xmlns="/xml/ns/javaee"

4. xmlns:xsi="/2001/XMLSchema-instance"

5. xsi:schemaLocation="/xml/ns/javaee

6. /xml/ns/javaee/web-app_2_">

7.

8. This is the description of my J2EE component

>

9.

name>This is the display name of my J2EE component

10. WechatServlet

11. Servlet

12.

13.

14. WechatServlet

15. /

16.

17.

18.

19.

20.

1.3 通过以上代码,我们已经实现了微信公众平台开发的框架,即开通开发者模

式并成功接入、接收消息和发送消息这三个步骤。

下面就讲解其核心部分——解析接收到的xml数据,并以文本类消息为例,通过图

灵机器人api接口实现智能回复。

2.1 首先看一下整体流程处理代码,包括:xml数据处理、调用图灵api、封装返回

的xml数据。

[java] view plaincopy

1. package s;

2. import ;

3. import eXmlEntity;

4. /**

5. * 微信xml消息处理流程逻辑类

6. * @author pamchen-1

7. *

8. */

9. public class WechatProcess {

10. /**

11. * 解析处理xml、获取智能回复结果(通过图灵机器人api接口)

12. * @param xml 接收到的微信数据

13. * @return 最终的解析结果(xml格式数据)

14. */

15. public String processWechatMag(String xml){

16. /** 解析xml数据 */

17. ReceiveXmlEntity xmlEntity = new ReceiveXmlProcess().getMsgEntity(

xml);

18.

19. /** 以文本消息为例,调用图灵机器人api接口,获取回复内容 */

20. String result = "";

21. if("text".endsWith(Type())){

22. result = new TulingApiProcess().getTulingResult(te

nt());

23. }

24.

25. /** 此时,如果用户输入的是“你好”,在经过上面的过程之后,result为

“你也好”类似的内容

26. * 因为最终回复给微信的也是xml格式的数据,所有需要将其封装为文本

类型返回消息

27. * */

28. result = new FormatXmlProcess().formatXmlAnswer(

mUserName(), serName(), result);

29.

30. return result;

31. }

32. }

2.2 解析接收到的xml数据,此处有两个类,和

,通过反射的机制动态调用实体类中的set方法,可

以避免很多重复的判断,提高代码效率,代码如下:

[java] view plaincopy

1. package ;

2. /**

3. * 接收到的微信xml实体类

4. * @author pamchen-1

5. *

6. */

7. public class ReceiveXmlEntity {

8. private String ToUserName="";

9. private String FromUserName="";

10. private String CreateTime="";

11. private String MsgType="";

12. private String MsgId="";

13. private String Event="";

14. private String EventKey="";

15. private String Ticket="";

16. private String Latitude="";

17. private String Longitude="";

18. private String Precision="";

19. private String PicUrl="";

20. private String MediaId="";

21. private String Title="";

22. private String Description="";

23. private String Url="";

24. private String Location_X="";

25. private String Location_Y="";

26. private String Scale="";

27. private String Label="";

28. private String Content="";

29. private String Format="";

30. private String Recognition="";

31.

32. public String getRecognition() {

33. return Recognition;

34. }

35. public void setRecognition(String recognition) {

36. Recognition = recognition;

37. }

38. public String getFormat() {

39. return Format;

40. }

41. public void setFormat(String format) {

42. Format = format;

43. }

44. public String getContent() {

45. return Content;

46. }

47. public void setContent(String content) {

48. Content = content;

49. }

50. public String getLocation_X() {

51. return Location_X;

52. }

53. public void setLocation_X(String locationX) {

54. Location_X = locationX;

55. }

56. public String getLocation_Y() {

57. return Location_Y;

58. }

59. public void setLocation_Y(String locationY) {

60. Location_Y = locationY;

61. }

62. public String getScale() {

63. return Scale;

64. }

65. public void setScale(String scale) {

66. Scale = scale;

67. }

68. public String getLabel() {

69. return Label;

70. }

71. public void setLabel(String label) {

72. Label = label;

73. }

74. public String getTitle() {

75. return Title;

76. }

77. public void setTitle(String title) {

78. Title = title;

79. }

80. public String getDescription() {

81. return Description;

82. }

83. public void setDescription(String description) {

84. Description = description;

85. }

86. public String getUrl() {

87. return Url;

88. }

89. public void setUrl(String url) {

90. Url = url;

91. }

92. public String getPicUrl() {

93. return PicUrl;

94. }

95. public void setPicUrl(String picUrl) {

96. PicUrl = picUrl;

97. }

98. public String getMediaId() {

99. return MediaId;

100. }

101. public void setMediaId(String mediaId) {

102. MediaId = mediaId;

103. }

104. public String getEventKey() {

105. return EventKey;

106. }

107. public void setEventKey(String eventKey) {

108. EventKey = eventKey;

109. }

110. public String getTicket() {

111. return Ticket;

112. }

113. public void setTicket(String ticket) {

114. Ticket = ticket;

115. }

116. public String getLatitude() {

117. return Latitude;

118. }

119. public void setLatitude(String latitude) {

120. Latitude = latitude;

121. }

122. public String getLongitude() {

123. return Longitude;

124. }

125. public void setLongitude(String longitude) {

126. Longitude = longitude;

127. }

128. public String getPrecision() {

129. return Precision;

130. }

131. public void setPrecision(String precision) {

132. Precision = precision;

133. }

134. public String getEvent() {

135. return Event;

136. }

137. public void setEvent(String event) {

138. Event = event;

139. }

140. public String getMsgId() {

141. return MsgId;

142. }

143. public void setMsgId(String msgId) {

144. MsgId = msgId;

145. }

146. public String getToUserName() {

147. return ToUserName;

148. }

149. public void setToUserName(String toUserName) {

150. ToUserName = toUserName;

151. }

152. public String getFromUserName() {

153. return FromUserName;

154. }

155. public void setFromUserName(String fromUserName) {

156. FromUserName = fromUserName;

157. }

158. public String getCreateTime() {

159. return CreateTime;

160. }

161. public void setCreateTime(String createTime) {

162. CreateTime = createTime;

163. }

164. public String getMsgType() {

165. return MsgType;

166. }

167. public void setMsgType(String msgType) {

168. MsgType = msgType;

169. }

170. }

[java] view plaincopy

1. package s;

2. import ;

3. import ;

4. import or;

5. import nt;

6. import ntHelper;

7. import t;

8. import eXmlEntity;

9. /**

10. * 解析接收到的微信xml,返回消息对象

11. * @author pamchen-1

12. *

13. */

14. public class ReceiveXmlProcess {

15. /**

16. * 解析微信xml消息

17. * @param strXml

18. * @return

19. */

20. public ReceiveXmlEntity getMsgEntity(String strXml){

21. ReceiveXmlEntity msg = null;

22. try {

23. if (() <= 0 || strXml == null)

24. return null;

25.

26. // 将字符串转化为XML文档对象

27. Document document = ext(strXml);

28. // 获得文档的根节点

29. Element root = tElement();

30. // 遍历根节点下所有子节点

31. Iterator iter = tIterator();

32.

33. // 遍历所有结点

34. msg = new ReceiveXmlEntity();

35. //利用反射机制,调用set方法

36. //获取该实体的元类型

37. Class c = e("eXmlEntity");

38. msg = (ReceiveXmlEntity)tance();//创建这个实体的对象

39.

40. while(t()){

41. Element ele = (Element)();

42. //获取set方法中的参数字段(实体类的属性)

43. Field field = laredField(e());

44. //获取set方法,e())获取它的参数数据类型

45. Method method = laredMethod("set"+e(), fi

e());

46. //调用set方法

47. (msg, t());

48. }

49. } catch (Exception e) {

50. // TODO: handle exception

51. n("xml 格式异常: "+ strXml);

52. tackTrace();

53. }

54. return msg;

55. }

56. }

2.3 调用图灵机器人api接口,获取智能回复内容:

[java] view plaincopy

1. package s;

2. import ption;

3. import ortedEncodingException;

4. import oder;

5. import sponse;

6. import ProtocolException;

7. import t;

8. import ients;

9. import Utils;

10. import ception;

11. import ject;

12. /**

13. * 调用图灵机器人api接口,获取智能回复内容

14. * @author pamchen-1

15. *

16. */

17. public class TulingApiProcess {

18. /**

19. * 调用图灵机器人api接口,获取智能回复内容,解析获取自己所需结果

20. * @param content

21. * @return

22. */

23. public String getTulingResult(String content){

24. /** 此处为图灵api接口,参数key需要自己去注册申请,先以11111111

代替 */

25. String apiUrl = "/openapi/api?key=111111

11&info=";

26. String param = "";

27. try {

28. param = apiUrl+(content,"utf-8");

29. } catch (UnsupportedEncodingException e1) {

30. // TODO Auto-generated catch block

31. tackTrace();

32. } //将参数转为url编码

33.

34. /** 发送httpget请求 */

35. HttpGet request = new HttpGet(param);

36. String result = "";

37. try {

38. HttpResponse response = Default().execute(requ

est);

39. if(tusLine().getStatusCode()==200){

40. result = ng(ity());

41. }

42. } catch (ClientProtocolException e) {

43. tackTrace();

44. } catch (IOException e) {

45. tackTrace();

46. }

47. /** 请求失败处理 */

48. if(null==result){

49. return "对不起,你说的话真是太高深了……";

50. }

51.

52. try {

53. JSONObject json = new JSONObject(result);

54. //以code=100000为例,参考图灵机器人api文档

55. if(100000==("code")){

56. result = ing("text");

57. }

58. } catch (JSONException e) {

59. // TODO Auto-generated catch block

60. tackTrace();

61. }

62. return result;

63. }

64. }

2.4 将结果封装为微信规定的xml格式,并返回给1.1中创建的servlet接

口。

[java] view plaincopy

1. package s;

2. import ;

3. /**

4. * 封装最终的xml格式结果

5. * @author pamchen-1

6. *

7. */

8. public class FormatXmlProcess {

9. /**

10. * 封装文字类的返回消息

11. * @param to

12. * @param from

13. * @param content

14. * @return

15. */

16. public String formatXmlAnswer(String to, String from, String content) {

17. StringBuffer sb = new StringBuffer();

18. Date date = new Date();

19. ("

20. (to);

21. ("]]>

22. (from);

23. ("]]>");

24. (e());

25. ("

>

26. (content);

27. ("]]>0");

28. return ng();

29. }

30. }

总结,以上便是微信公众平台开发的全部流程,整体来看并不复杂,要非常感谢图灵

机器人提供的api接口,帮我们解决了智能回复这一高难度问题。其他类型的消息处理与

示例中类似,有兴趣的开发者可以联系我进行交流学习,希望本文对大家有所帮助。


本文标签: 微信 接口 消息 平台 开发