Public platform for developing Java letter (X) - Get the micro-channel user information

Previous article there are a series of development article that micro-letters, including token acquisition, menu creation, etc., in this one will be about how to obtain micro-channel users of the micro-channel public platform, on the one we have said micro-channel users and the link between the public account micro-channel can openid association, so here we are using openid user to acquire micro-channel information. And realize two simple scenarios application :( a) When a new micro-channel users pay attention to our micro-channel public platform when we auto-reply a graphic message, then the message in a graphic titled: [Dear: XXX, hello ! ], And teletext messages in the user's picture is micro-channel head, as shown :( two) PC interface displays user's nickname, gender, avatar

 

(A) concern passive reply achieve graphic message.

For information on obtaining documentation micro-channel user information, we can refer to: http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html  .

Get achieve (a) a user message micro letter

After the number of followers and generate public message exchange, available to the public number of followers OpenID (micro signal encrypted, each user is unique to each public OpenID numbers for different public numbers, different users of the same openid ). No public can get through this interface OpenID basic user information, including nickname, avatar, gender, city, language and attention time according to.

http request method: GET https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

Here I wrote a class method GetUseInfo.java, in the method we only need to pass openid to return (nickname, image, gender [other] parameters available on their own), the code is implemented as follows:

 1 package com.gede.wechat.common;
 2 import java.util.HashMap;
 3 import com.gede.web.util.GlobalConstants;
 4 import com.gede.wechat.response.UserInfo;
 5 import com.gede.wechat.util.HttpUtils;
 6  
 7 import net.sf.json.JSONObject;
 8 /**
 9 * @author gede
10 * @version date:2019年5月29日 上午11:52:26
11 * @description :
12 */
13 public class GetUseInfo {
14     /**
15       * @Description: obtaining user information through micro-channel openid
 16       * @param  @param openid
 17       * @param  @return 
18       * @param  @throws Exception   
 19       * @author dapengniao
 20       * @date 2:01 2016 Nian 3 afternoon of May 18 : 30
 21 is       * / 
22 is      public  static the HashMap <String, String> Openid_userinfo (String OpenID)
 23 is              throws Exception {
 24          the HashMap <String, String> the params = new new the HashMap <String, String> ();
 25         UI = the UserInfo null ;
 26 is          params.put ( "the access_token" ,
 27                  GlobalConstants.getInterfaceUrl ( "the access_token"));   // the acquired timer token 
28          params.put ( "OpenID", OpenID);   // need to obtain user OpenID 
29          params.put ( "lang", "zh_CN" );
 30          String subscribers = HttpUtils.sendGet (
 31 is                  GlobalConstants.getInterfaceUrl ( "OpenidUserinfoUrl" ), the params);
 32          System.out.println (subscribers);
 33 is          params.clear ();
 34 is          //Here return parameters take only a nickname, avatar, and gender 
35          String = JSONObject.fromObject Nickname (subscribers) .getString ( "Nickname" );
 36          String headimgurl = JSONObject.fromObject (subscribers) .getString ( "headimgurl" );
 37 [          String = JSONObject.fromObject Sex (subscribers) .getString ( "Sex" );
 38 is         
39          UI = new new the UserInfo (nickname, headimgurl, Sex);
 40          params.put ( "nickname" ,
 41 is                  nickname); // Nick 
42 is          params.put ( "headimgurl" ,
 43 is                  headimgurl);  // image 
44         params.put("sex", sex);  //性别
45        
46         return params;
47     }
48 }

(B) focus on the message reply graphic realization

In the first part has said generating a message [after interaction with the public in a number of followers, number of available public OpenID followers], get followers openid event is the user's attention to events in our scenario, we are also concerned about Followers passive event to reply graphic message that implementation process:

  • Openid acquired by focusing on events, call to get the user interface to obtain information related interfaces followers;

  • Set concerned about the graphic messages in the event of passive reply title and pictures, reply to followers;

Simple code to achieve the following:

 1 NewsMessage newmsg = new NewsMessage();
 2         newmsg.setToUserName(openid);
 3         newmsg.setFromUserName(mpid);
 4         newmsg.setCreateTime(new Date().getTime());
 5         newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
 6         if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // 关注事件
 7             System.out.println("==============这是关注事件!");
 8             try {
 9                 HashMap<String, String> userinfo = GetUseInfo.Openid_userinfo(openid);
10                 = Article This article was Article This article was new new Article This article was ();
 11                  article.setDescription ( "Welcome to the Goethe personal blog:! Growth rookie programmer Road"); // describe graphic message 
12                  article.setPicUrl (userinfo.get ( "headimgurl ")); // graphic picture messaging address 
13                  article.setTitle (" Dear: "+ userinfo.get (" nickname " ) +", hello ");! // graphic message header 
14                  article.setUrl ( "https://www.cnblogs.com/gede"); // graphic url link 
15                  List <Article This article was> List = new new the ArrayList <Article This article was> ();
 16                  List.add (Article This article was);//Here we are sending a single graphic, if you need to send multiple graphics here to list more added to Article! 
. 17                  newmsg.setArticleCount (list.size ());
 18 is                  newmsg.setArticles (List);
 . 19                  return MessageUtil.newsMessageToXml (NewMsg);
 20 is              } the catch (Exception E) {
 21 is                  // the TODO Auto-Generated the catch Block 
22 is                  the System.out .println ( "==== amount of code problems ☺!" );
 23              }
 24-  
25          }

Ultimately, we can take a look at our achievements here in order to see the effect is very intuitive to cancel my attention and then focus again, as shown below:

(B) pc user interface display

(A) adding jsp page need to use.

① add home.jsp in webi-nfo directory. Simple home screen to jump, why not just use the interface to add after the jump friendly code.

 1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 2 <%@ page session="false" %>
 3 <html>
 4   <head>
 5   </head>
 6   <body>
 7     <h1>Welcome to Mychat</h1>
 8     <a href="<c:url value="/userinfo" />">UserInfo</a> | 
 9   </body>
10 </html>

②在webi-nfo目录下添加userinfo.jsp。 通过上面被动回复我们不难发现,获取用户信息最重要的是要得到相关公众号对应的openid,所以这里来一个简单的表单提交。

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 3 <html>
 4   <head>
 5     <title>输入OppenId</title>
 6   </head>
 7   <body>
 8       <form action="userinfo/register" >
 9           <h1>请输入用户openid:<input name="openid" type="text"></h1>
10           <input type="submit">
11       </form>
12   </body>
13 </html>

③在webi-nfo目录下添加user.jsp。这个界面是用来请求成功以后,展示用户信息的界面。

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 3 <html>
 4   <head>
 5     <title>User</title>
 6   </head>
 7   <body>
 8     <div class="userView">
 9       <div class="spittleMessage"><c:out value="${gui.nickname}" /></div>
10       <div>
11         <span class="spittleTime"><c:out value="${gui.sex}" /></span>
12       </div>
13         <img alt="" width="300" height="300" src="${gui.headimgurl}">
14     </div>
15   </body>
16 </html>

(二)在GetUseInfo中添加Openid_userinfo1方法。这里起名比较随便。之前我们获取用户信息是定义了一个静态static final类,但是当放在mvc中时,就有点突兀。所以我们重新写了一个名为Openid_userinfo1的类方法。其返回类型时一个userinfo类。这里我们使用userinfo类来对查到的用户信息进行封装,返回。

①添加UserInfo实体类

 1 package com.gede.wechat.message.response;
 2 /**
 3 * @author gede
 4 * @version date:2019年5月29日 上午11:54:03
 5 * @description :
 6 */
 7 public class UserInfo {
 8     public String nickname;    //用户昵称
 9     public String headimgurl;  //头像
10     public String sex;            //性别
11     public UserInfo(String nickname, String headimgurl, String sex) {
12         super();
13         this.nickname = nickname;
14         this.headimgurl = headimgurl;
15         this.sex = sex;
16     }
17     public String getNickname() {
18         return nickname;
19     }
20     public void setNickname(String nickname) {
21         this.nickname = nickname;
22     }
23     public String getHeadimgurl() {
24         return headimgurl;
25     }
26     public void setHeadimgurl(String headimgurl) {
27         this.headimgurl = headimgurl;
28     }
29     public String getSex() {
30         return sex;
31     }
32     public void setSex(String sex) {
33         this.sex = sex;
34     }
35     
36 }

②在GetUseInfo中添加Openid_userinfo1方法,简单代码如下:

 1 public UserInfo Openid_userinfo1(String openid)
 2             throws Exception {
 3         HashMap<String, String> params = new HashMap<String, String>();
 4         UserInfo ui=null;
 5         params.put("access_token",
 6                 GlobalConstants.getInterfaceUrl("access_token"));  //定时器中获取到的token
 7         params.put("openid", openid);  //需要获取的用户的openid
 8         params.put("lang", "zh_CN");
 9         String subscribers = HttpUtils.sendGet(
10                 GlobalConstants.getInterfaceUrl("OpenidUserinfoUrl"), params);
11         System.out.println(subscribers);
12         params.clear();
13         //这里返回参数只取了昵称、头像、和性别
14         String nickname=JSONObject.fromObject(subscribers).getString("nickname");
15         String headimgurl=JSONObject.fromObject(subscribers).getString("headimgurl");
16         String sex=JSONObject.fromObject(subscribers).getString("sex");
17        
18         ui=new UserInfo(nickname,headimgurl,sex);
19         params.put("nickname",
20                 nickname); //昵称
21         params.put("headimgurl",
22                 headimgurl);  //图像
23         params.put("sex", sex);  //性别
24        
25         return ui;
26     }

(三)配置我们相关的controller。

①首先我们添加houme解析试图。简单代码如下,有不懂的可以去看我下的Spring,里面有详解。

package com.gede.wechat.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@Controller
public class HomeController {
    @RequestMapping(value="/",method=GET)
    public String home(){
        //首页解析为home.jsp
        return "home";
    }
}

①再定义我们的GetUserControllerh获取信息控制器,简单代码如下:

 1 package com.gede.wechat.controller;
 2 import javax.servlet.http.HttpServletRequest;
 3 import static org.springframework.web.bind.annotation.RequestMethod.GET;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.ui.Model;
 7 import org.springframework.web.bind.annotation.PathVariable;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RequestMethod;
10 
11 import com.gede.wechat.common.GetUseInfo;
12 import com.gede.wechat.menu.MenuMain;
13 
14 
15 /**
16 * @author gede
17 * @version date:2019年5月29日 下午12:04:08
18 * @description :
19 */
20 @Controller
21 @RequestMapping("/userinfo")
22 public class GetUserController {
23     private GetUseInfo gui;
24     @RequestMapping(method=RequestMethod.GET)
25     public String userinfo(){
26         //响应超链接,返回userinfo.jsp
27         return "userinfo";
28     }
29     @RequestMapping(value="/register",method=RequestMethod.GET)
30     public String register(HttpServletRequest request){
31         //通过request获取input中提交的openid
32         String openid=request.getParameter("openid");
33         //openid为参数的重定向转发
34         return "redirect:/userinfo/"+openid;
35     }
36     @RequestMapping(value="/{openid}")
37     public String search(@PathVariable("openid") String openid,Model model) throws Exception{
38         //@PathVariable通过路径解析来获取传过来的openid
39         gui=new GetUseInfo();
40         model.addAttribute("gui", gui.Openid_userinfo1(openid));
41         return "user";
42     }
43 }

这个时候我们的PC界面配置也就完成了。运行项目。在浏览器地址栏中输入:http://zqfbk.iok.la/mychat.就可以访问到了。

到这里通过openid获取用户信息的实现就结束啦。

Guess you like

Origin www.cnblogs.com/gede/p/10945486.html