How to obtain and save the interface call credentials, the following for you to introduce
I. Description
* Please refer to the first two articles for more information.
* This article is divided into three parts:
Function and explanation of interface call voucher Access_token
How to obtain an interface call voucher Access_token
How to implement the "medium-managed server" described in the micro-letter document to save Access_token
* The end of this article will give the first three articles including this article all the demo source code
Why to get and save an interface call voucher Access_token
• Start development-Get interface call credentials
◦ Document address:http://mp.weixin.qq.com/wiki/14/9f9c82c1af308e3b14ba9b973f99a8ba.html
• The official website document gives this explanation:
◦access_token is the public number's globally unique ticket, the public number calls each interface to use the Access_token. Developers need to be properly saved. Access_token storage should be reserved for at least 512 character spaces. The validity period of the Access_token is currently 2 hours and needs to be refreshed periodically, and repeated acquisition will cause the last acquired access_token to fail.
Understand
◦ We simply flip through the document to find that many advanced features, such as custom menus, material management, user management, account management, and other advanced feature request links have the "? Access_token=token" parameter, which is the global invocation parameter, Micro-letter backstage need to be based on this parameter identification, to ensure the security of our micro-credit public number.
◦ In order to prevent the public number of program errors caused by micro-server load anomaly, by default, each public number call interface can not exceed a certain limit, where the micro-letter limit 2000 times a day. So, if we want to call this parameter frequently, we need the developer to save it manually, and each access_token is valid for 2 hours.
Get interface Call Voucher Access_token
• The official website document gives this explanation:
◦ Interface Call Request description
HTTP request mode: Get
Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
return Description
Normally, the micro-letter will return the following JSON packet to the public number:
{"Access_token": "Access_token", "expires_in": 7200}
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):
{"Errcode": 40013, "errmsg": "Invalid AppID"}
Understand
◦get Request, this method can be implemented directly locally. Because it's just a normal get request, it's similar to accessing a URL. Therefore, you do not need to upload this part of the code to the server can be directly manipulated.
The ◦HTTP request protocol is a GET request, stating that we need to fetch the return stream through a obtain request, and the return stream is a JSON form. We need to carry three parameters when we call: Grant_type, AppID, Secret. Among them AppID and secret are the key parameters of our micro-letter public number, which have been elaborated in the previous article. The results of the return are divided into correct and erroneous results. "Baidu: JSON"
◦ In fact, we can enter the example of the document given directly in the address bar:Https://api.weixin.qq.com/cgi-bin/token? Grant_type=client_credential&appid=appid&secret=appsecret, we will see this message: "{Errcode": 40013, "errmsg": " Invalid AppID hint: [PQKL0120IC11] "}" because this is an invalid request and returns the wrong result.
◦ When we replace the above two parameters with our test number AppID and Appsecret, we see this message: "{" Access_token ":" Xrllr3fnf...badamio "," expires_in ": 7200}" to represent success.
◦ Now we get the return stream through the Java code, fetch the Access_token.
• Achieve
Private static final Long Max_time = 7200 * 1000;//Micro-letter allows maximum Access_token active time (ms) private static final String TAG = "Weixina Pitest "//TAG private static final String APPID =" Wx889b****b3666b0b8 ";//APPID private static final String Secert =" 6d
A7676***F0A9F15FBF06027856BB "//Secret Key * * This test case demonstrates how to obtain the Access_token.
* Access_token is the public number's globally unique ticket, the public number calls each interface to use the Access_token. * * @Test public void Getaccess_token () throws IOException {//Stitching API required Httpsurl link String urlstring = "Https://api.weix
In.qq.com/cgi-bin/token?grant_type=client_credential&appid= "+ AppID +" &secret= "+ SECERT;
Create a URL url requrl = new URL (urlstring);
Fetch link Httpsurlconnection httpsconn = (httpsurlconnection) requrl. OpenConnection ();
Gets the input stream of the connection to read the response content InputStreamReader ISR = new InputStreamReader (Httpsconn.getinputstream ());
Read the server's response content and display char[] chars = new char[1024];
String Reslut = "";
int Len; while (len = Isr.read (chars))!=-1) {Reslut + = new String (cHARs, 0, Len);
} isr.close (); * * Convert JSON into JavaBean.
Introduction of the third party Jar:gson/Gson Gson = new Gson ()//To convert fetched JSON to Java Bean//NOTE: Access_token Access_token is a created by yourself JavaBean
Access_token Access_token = Gson.fromjson (Reslut, New Access_token (). GetClass ()); if (Access_token.getaccess_token ()!= null) {System.out.println ("obtained access_token is:" + Access_token.getaccess_
Token ());
System.out.println ("The Access_token's effective time is:" + access_token.getexpires_in () + "s");
else {System.out.println (TAG + "Get Access_token failed, please check");
}
}
Save Interface Call Voucher Access_token
• Train of Thought
Store the acquired Access_token and current time in file, take out the time difference between the current time and the record in the store, if it is greater than max_time, retrieve it, and replace the acquired storage to file with the original content, if less than Max_time, Direct access.
• Achieve
* * This method realizes obtaining access_token, saving and saving only 2 hours access_token. If more than two hours to regain, if not more than two hours, direct access. The method relies on the *: public static String Getaccesstoken (); * * Thinking: Storing the acquired Access_token and current time in file, * Determining the current time and the time of record in the store when taking out
The time difference, if greater than Max_time, is retrieved, and the acquired storage to file is replaced with the original content *, if less than max_time, directly obtained.
* * @Test public void Getsavedaccess_token () throws IOException {Gson Gson = new Gson ();
String Maccess_token = null;//need to get Access_token file = new file ("Temp_access_token.temp");//Access_token saved location
If the file does not exist, create an if (!file.exists ()) file.createnewfile ();
If the file size is equal to 0, the first use is to deposit Access_token if (file.length () = = 0) {Maccess_token = Getaccesstoken ();
FileOutputStream fos = new FileOutputStream (file, false);//Do not allow append access_token at = new Access_token ();
At.setaccess_token (Maccess_token);
At.setexpires_in (System.currenttimemillis () + "");
String json = Gson.tojson (at);
Fos.write ((JSON). GetBytes ());
Fos.close ();
} else { Read the contents of the file FileInputStream fis = new FileInputStream (file);
Byte[] B = new byte[2048];
int len = Fis.read (b); String mjsonaccess_token = new String (b, 0, Len);//Read to the contents of the file Access_token Access_token = Gson.fromjson (mjsonaccess_t
Oken, New Access_token (). GetClass ());
if (access_token.getexpires_in ()!= null) {Long savetime = Long.parselong (access_token.getexpires_in ());
Long nowtime = System.currenttimemillis ();
Long remiantime = Nowtime-savetime;
System.out.println (TAG + "time lag:" + remiantime); if (Remiantime < max_time) {Access_token at = Gson.fromjson (Mjsonaccess_token, New Access_toke
N (). GetClass ());
Maccess_token = At.getaccess_token ();
else {Maccess_token = Getaccesstoken ();
FileOutputStream fos = new FileOutputStream (file, false);//Do not allow append access_token at = new Access_token (); At.setaccess_token (maccess_token);
At.setexpires_in (System.currenttimemillis () + "");
String json = Gson.tojson (at);
Fos.write ((JSON). GetBytes ());
Fos.close ();
}} System.out.println ("Get Access_token is:" + Maccess_token); /* * Get the Micro-server Accesstoken. This section is consistent with Getaccess_token () and is no longer commented on/public static string Getaccesstoken () {String urlstring = ' Https://api.weixin.
Qq.com/cgi-bin/token?grant_type=client_credential&appid= "+ AppID +" &secret= "+ secert;
String reslut = null;
try {URL requrl = new URL (urlstring);
Httpsurlconnection httpsconn = (httpsurlconnection) requrl. OpenConnection ();
InputStreamReader ISR = new InputStreamReader (Httpsconn.getinputstream ());
char[] chars = new char[1024];
Reslut = "";
int Len;
while (len = Isr.read (chars))!=-1) {Reslut + = new String (chars, 0, Len);
} isr.close (); catch (IOException E) {E.printstacktrace ();
} Gson Gson = new Gson ();
Access_token Access_token = Gson.fromjson (Reslut, New Access_token (). GetClass ());
if (Access_token.getaccess_token ()!= null) {return Access_token.getaccess_token ();
else {return null;
}
}
Top three article demo source code: Http://xiazai.jb51.net/201606/yuanma/WeixinApiDemo (jb51.net). rar
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.