Development of micro-credit public platform Java version of the micro-letter to obtain user basic information _java

Source: Internet
Author: User
Tags error code openid stringbuffer

After a message is interacted with the public number, the public number can obtain the followers ' OpenID (encrypted micro-signal, each user's OpenID is unique to each public number). For different public numbers, the same user's OpenID is different.

The public number can be used to obtain basic user information based on OpenID, including nicknames, Avatar, sex, city, language and time of concern.

Developers can use OpenID to get basic user information. Please use the HTTPS protocol.

We can look at the official documentation: get the user's basic information.

Interface Call Request Description

HTTP request mode: Get

Https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

Parameter description

Parameters whether you must Description
Access_token Is Calling interface Credentials
Openid Is Identification of the ordinary user, unique to the current public number
Lang Whether Return to the country language version, ZH_CN simplified, zh_tw traditional, en English

Return description

Normally, the micro-letter will return the following JSON packet to the public number:

 {
  "subscribe": 1, 
  "OpenID": "o6_bmjrptlm6_2sgvt7hmzopfl2m", 
  "nickname": "Band", 
  "sex": 1, 
  " Language ":" ZH_CN "," City 
  ":" Guangzhou ", 
  " province ":" Guangdong ", 
  " Country ":" China ", 
  " Headimgurl ":  " http:// wx.qlogo.cn/mmopen/ g3monuztnhkdmzicilibx6iafqac56vxlsufpb6n5wksyvy0chqkkiajsgq1dzutogvllrhjberqq4emsv84eavhiaiceqxibjxcfhe/0 ", 
  "Subscribe_time": 1382694957,
  "Unionid": "O6_BMASDASDSAD6_2SGVT7HMZOPFL"
  "remark": "",
  " GroupID ": 0

Parameter description

Parameters Description
Subscribe Whether the user subscribes to the public number identification value of 0 o'clock indicates that the user is not paying attention to the public number and that the rest of the information is not drawn.
Openid Identification of the user, unique to the current public number
Nickname User's nickname
Sex The user's sex, the value of 1 o'clock is male, the value of 2 o'clock is female, the value of 0 o'clock is unknown
City The city where the user is located
Country The country where the user is located
Province The province where the user is located
Language User's language, Simplified Chinese for ZH_CN
Headimgurl User Avatar, the last value represents the size of the square head (there are 0, 46, 64, 96, 132 value Optional, 0 represents 640*640 square avatar), the user does not have the Avatar when the item is empty. If the user changes the avatar, the original avatar URL will fail.
Subscribe_time User focus time, time stamp. If the user has a lot of attention, then take the final attention time
Unionid The field will only appear if the user binds the public number to the micro-trust Open platform account. See: Get User's personal information (Unionid mechanism)
Remark Public operator's comments to fans, public number operators can add notes to fans in the micro-credit public platform user management community
GroupID The group ID where the user is located

In the case of an error, the micro-letter returns information such as the error code, and the JSON packet example is as follows (the example is an AppID invalid error):

 

Based on the above information, we define a user information class to store the user's basic information.

Package Com.souvc.weixin.pojo;
/** * Class Name: Weixinuserinfo </br> * Description: Basic information for micro-trust users </br> * Developer: SOUVC </br> * Date Created: 2015-11-27 </br>
  * Release version: V1.0 </br> * * public class Weixinuserinfo {//user's identity private String openId;
  The state of concern (1 is concerned, 0 is not concerned), do not receive the rest of the information when the private int subscribe; User focus time, time stamp.
  If the user has a lot of attention, then take the last attention time private String subscribetime;
  Nickname Private String nickname;
  The user's gender (1 is male, 2 is female, 0 is unknown) private int sex;
  Private String country in the country where the user is located;
  User province private String province;
  Private String City of the user's town;
  User's language, Simplified Chinese for zh_cn private String language;
  User Avatar private String headimgurl;
  Public String Getopenid () {return openId;
  public void Setopenid (String openId) {This.openid = OpenID;
  public int Getsubscribe () {return subscribe;
  The public void setsubscribe (int subscribe) {this.subscribe = subscribe;
  Public String Getsubscribetime () {return subscribetime; } public void SETsubscribetime (String subscribetime) {this.subscribetime = Subscribetime;
  Public String Getnickname () {return nickname;
  } public void Setnickname (String nickname) {this.nickname = nickname;
  public int Getsex () {return sex;
  The public void setsex (int sex) {this.sex = sex;
  Public String Getcountry () {return country;
  } public void Setcountry (String country) {this.country = country;
  Public String getprovince () {return province;
  } public void Setprovince (String province) {this.province = province;
  Public String getcity () {return city;
  public void Setcity (String city) {this.city = city;
  Public String GetLanguage () {return language;
  } public void SetLanguage (String language) {this.language = language;
  Public String Getheadimgurl () {return headimgurl;
  } public void Setheadimgurl (String headimgurl) {this.headimgurl = Headimgurl;  }
}

Let's take a look at the interface to get user information:

Https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

According to the analysis, it takes a token to get the user's basic information.

Package Com.souvc.weixin.pojo;
/**
* Class name: Token </br>
* Description: Voucher </br>
* Developer: SOUVC </br>
* Date Created: 2015-11-27 </br>< c6/>* Release version: V1.0 </br>
/public class Token {
  //interface Access voucher
  private String accesstoken;
  Voucher validity period, Unit: second
  private int expiresin;
  Public String Getaccesstoken () {return
    accesstoken;
  }
  public void Setaccesstoken (String accesstoken) {
    this.accesstoken = Accesstoken;
  }
  public int Getexpiresin () {return
    expiresin;
  }
  public void Setexpiresin (int expiresin) {
    this.expiresin = expiresin;
  }
}

HTTPS request, required trust manager

Package com.souvc.weixin.util;
Import java.security.cert.CertificateException;
Import java.security.cert.X509Certificate;
Import Javax.net.ssl.X509TrustManager;
/**
* Class name: Myx509trustmanager </br>
* Description: Trust manager </br>
* Developer: SOUVC </br>
* Create time: 2015-11-27 </br>
* Release version: V1.0 </br>/Public
class Myx509trustmanager implements X509trustmanager {
  //Check client certificate public
  void Checkclienttrusted (x509certificate[] chain, String authtype) Throws Certificateexception {
  }
  /Check server-side certificate public
  void Checkservertrusted (x509certificate[] chain, String authtype) throws certificateexception {
  }
  //Return of trusted X509 certificate array public
  x509certificate[] Getacceptedissuers () {return
    null;
  }
}

Encapsulates a common class:

Package com.souvc.weixin.util;
Import Java.io.BufferedReader;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.io.UnsupportedEncodingException;
Import java.net.ConnectException;
Import Java.net.URL;
Import javax.net.ssl.HttpsURLConnection;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.SSLSocketFactory;
Import Javax.net.ssl.TrustManager;
Import net.sf.json.JSONException;
Import Net.sf.json.JSONObject;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Com.souvc.weixin.pojo.Token; /** * Class Name: Commonutil </br> * Description: General Tools </br> * Developers: SOUVC </br> * creation time: 2015-11-27 </br> * Release: V
  1.0 </br> * * Public class Commonutil {private static Logger log = Loggerfactory.getlogger (Commonutil.class); Voucher fetch (GET) public final static String Token_url = "Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_
  Credential&appid=appid&secret=appsecret "; /** * Send HTTPS request * * @pAram Requesturl Request Address * @param Requestmethod request method (GET, POST) * @param outputstr submitted data * @return Jsonobject (via Jsonob Ject.get (key) to get the property value of the JSON object)/public static Jsonobject Httpsrequest (String requesturl, String Requestmethod, Strin
    G outputstr) {jsonobject jsonobject = null;
      try {//Create the Sslcontext object and initialize trustmanager[] tm = {new Myx509trustmanager ()} with our specified trust manager;
      Sslcontext Sslcontext = sslcontext.getinstance ("SSL", "Sunjsse");
      Sslcontext.init (NULL, TM, New Java.security.SecureRandom ());
      The Sslsocketfactory object Sslsocketfactory SSF = Sslcontext.getsocketfactory () is obtained from the above Sslcontext object;
      URL url = new URL (requesturl);
      Httpsurlconnection conn = (httpsurlconnection) url.openconnection ();
      Conn.setsslsocketfactory (SSF);
      Conn.setdooutput (TRUE);
      Conn.setdoinput (TRUE);
      Conn.setusecaches (FALSE);
      Set the request mode (Get/post) Conn.setrequestmethod (Requestmethod); Writes data to an output stream when OUTPUTSTR is not null if (null!= outputstr) {OutputStream outputstream = Conn.getoutputstream ();
        Note the encoding format outputstream.write (outputstr.getbytes ("UTF-8"));
      Outputstream.close ();
      ///reads the return content from the input stream InputStream InputStream = Conn.getinputstream ();
      InputStreamReader InputStreamReader = new InputStreamReader (InputStream, "utf-8");
      BufferedReader BufferedReader = new BufferedReader (InputStreamReader);
      String str = NULL;
      StringBuffer buffer = new StringBuffer ();
      while (str = Bufferedreader.readline ())!= null) {buffer.append (str);
      }//release of resources bufferedreader.close ();
      Inputstreamreader.close ();
      Inputstream.close ();
      InputStream = null;
      Conn.disconnect ();
    Jsonobject = Jsonobject.fromobject (buffer.tostring ());
    catch (connectexception CE) {log.error ("Connection timeout: {}", CE);
    catch (Exception e) {log.error ("https request exception: {}", E);
  return jsonobject; /** * Get interface AccessCertificate * * @param appid certificate * @param appsecret Key * @return/public static Token GetToken (String AppID, Stri
    ng Appsecret) {Token Token = null;
    String Requesturl = Token_url.replace ("APPID", APPID). Replace ("Appsecret", Appsecret);
    Initiates a GET request to obtain a voucher Jsonobject Jsonobject = httpsrequest (Requesturl, "gets", null);
        if (null!= jsonobject) {try {token = new token ();
        Token.setaccesstoken (jsonobject.getstring ("Access_token"));
      Token.setexpiresin (Jsonobject.getint ("expires_in"));
        catch (Jsonexception e) {token = null; Get token failed log.error ("Get token failed errcode:{} errmsg:{}", Jsonobject.getint ("Errcode"), Jsonobject.getstring ("Errms
      G "));
  } return token; /** * URL encoding (UTF-8) * * @param source * @return/public static string UrlEncodeUTF8 (string source)
    {String result = source;
    try {result = Java.net.URLEncoder.encode (source, "Utf-8"); } catch (Unsupportedencodingexception e) {e.printstacktrace ();
  return result; /** * Based on content type to determine file name extension * * @param contentType Content Type * @return/public static string Getfileext (string
    ContentType) {String fileext = "";
    if ("Image/jpeg". Equals (ContentType)) Fileext = ". jpg";
    else if ("Audio/mpeg". Equals (ContentType)) Fileext = ". mp3";
    else if ("Audio/amr". Equals (ContentType)) Fileext = ". Amr";
    else if ("Video/mp4". Equals (ContentType)) Fileext = ". mp4";
    else if ("Video/mpeg4". Equals (ContentType)) Fileext = ". mp4";
  return fileext; }
}

How to obtain basic user information:

/** * Obtain user information * * @param accesstoken Interface Access voucher * @param openId User ID * @return weixinuserinfo/Public s
    Tatic weixinuserinfo GetUserInfo (String accesstoken, String openId) {weixinuserinfo = null; Mosaic request Address String Requesturl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=
    OPENID ";
    Requesturl = Requesturl.replace ("Access_token", Accesstoken). Replace ("OpenID", OpenID);
    Obtain user information Jsonobject Jsonobject = Commonutil.httpsrequest (Requesturl, "get", null);
        if (null!= jsonobject) {try {weixinuserinfo = new weixinuserinfo ();
        User's identification Weixinuserinfo.setopenid (jsonobject.getstring ("OpenID"));
        The state of concern (1 is concerned, 0 is not concerned), without attention to obtain the rest of the information Weixinuserinfo.setsubscribe (Jsonobject.getint ("subscribe"));
        User Focus time Weixinuserinfo.setsubscribetime (jsonobject.getstring ("Subscribe_time")); Nickname Weixinuserinfo.setnickname (jsonobject.getstring ("NIckname "));
        The user's gender (1 is male, 2 is female, 0 is unknown) weixinuserinfo.setsex (Jsonobject.getint ("Sex"));
        User Country Weixinuserinfo.setcountry (jsonobject.getstring ("Country"));
        User Province Weixinuserinfo.setprovince (jsonobject.getstring ("province"));
        The user is located in the city Weixinuserinfo.setcity (jsonobject.getstring);
        User's language, Simplified Chinese is zh_cn weixinuserinfo.setlanguage (jsonobject.getstring ("language"));
      User Avatar Weixinuserinfo.setheadimgurl (jsonobject.getstring ("Headimgurl")); catch (Exception e) {if (0 = Weixinuserinfo.getsubscribe ()) {Log.error ("user {} has canceled attention", Weixinuserinfo.)
        Getopenid ());
          else {int errorcode = Jsonobject.getint ("Errcode");
          String errormsg = jsonobject.getstring ("errmsg");
        Log.error ("Get user information failed errcode:{} errmsg:{}", ErrorCode, errormsg);
  }} return weixinuserinfo;  }

Method of testing: note Replace the following with your own AppID and secret keys.

public static void Main (String args[]) {
    //Get Interface Access voucher
    String Accesstoken = Commonutil.gettoken ("xxxx", "xxxx"). Getaccesstoken ();
    /**
     * Obtain user information * *
    weixinuserinfo user = GetUserInfo (accesstoken, "ook-yujvd9geegh6nrien-gnlrvw");
    System.out.println ("OpenID:" + User.getopenid ());
    System.out.println ("Attention Status:" + User.getsubscribe ());
    SYSTEM.OUT.PRINTLN ("Attention time:" + user.getsubscribetime ());
    System.out.println ("nickname:" + User.getnickname ());
    System.out.println ("Sex:" + user.getsex ());
    System.out.println ("Country:" + user.getcountry ());
    System.out.println ("Province:" + user.getprovince ());
    System.out.println ("City:" + user.getcity ());
    System.out.println ("Language:" + user.getlanguage ());
    System.out.println ("Avatar:" + user.getheadimgurl ());
  

The effect is as follows:

Openid:ook-yujvd9geegh6nrien-gnlrvw
Attention Status: 1
Focus Time: 1449021142
Nickname: Less Wind
Sex: 1
Country: China
Province: Guangdong
City: Guangzhou
Language: ZH_CN
Avatar: http://wx.qlogo.cn/mmopen/ lozievyfca7azq7ckiamdpqicudngdec0nzb7zaljdl3tzfvfehwm1afqexnicnideh0iqytt0nrip06ibg4w5wflasfffx9qqib0/0

The above content to introduce the micro-trust public platform for the development of real Java version of the micro-letter to obtain user information, I hope this article to share the future work of all of you to learn help, and thank you all the time has been on the cloud-Habitat community website support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.