1. Préface
Les trois paramètres qui sont finalement utilisés pour la vérification des appels d'interface WeChat:
Ensuite, le code détaillé pour obtenir ces trois paramètres sera donné. L'environnement de cet article est Eclipse + Maven.
Les technologies utilisées dans cet article HttpClient, JSON String to Map, SHA1 Encryption
2. Le package de pot requis
Les packages dont dépend maven sont:
1. Dépendance du package httpclient
<Dedency> <ProupId> org.apache.httpComponents </rom grouped> <ArtifActid> httpcore </retifactid> <version> 4.4.3 </DERNIERSE> </DENDENCENCE> <Dendency> <ProupId> Org.apache.httpConents </proupId> <ArtifActid> httpclient </tifactId> <version> 4.5.1 </ version> </ dépendance>
2. JSON à cartographier les dépendances de packages associés
<Dedency> <GroupId> net.sf.json-lib </proupId> <Artifactid> json-lib </ artifactid> <version> 2.4 </ version> <prousifier> jdk15 </slassifier> </dependency> <dependency> <prousifier> xom </proupId> <prifactive> xom </tatifactid> <fri version> 1,2.5 <frartence> xom </ artifactid>
3. Résultats de l'opération
4. Code détaillé
package com.luo.util; import java.io.ioException; import java.io.unsupportedEncodingException; import java.security.messagedigest; import java.security.nosuchalgorithmexception; import java.util.arrayList; import java.util.hashmap; import java. java.util.List;import java.util.Map;import java.util.Set;import java.util.UUID;import net.sf.json.JSONObject;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.parseException; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.entity.urlencodedFormentity; import org.apache.http.client.Methods.httpget; import org.apache.http.client.Methods.htt; org.apache.http.client.methods.httpurirequest; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.mesage.protocol.httpair; import org.apache.http.protocol.http; import org.apache.http.util.entityutils; classe publique httpxmlClient {public static static post (string url, map <string, string> params) {DefaulthTTPClient httpclient = new defaulthttpclient (); String Body = NULL; HTTPPOST POST = POSTFORM (URL, PARAMS); Body = invoke (httpclient, post); httpClient.getConnectionManager (). Shutdown (); corps de retour; } public static String get (string url) {defaulthTTPClient httpClient = new defaulthTTPClient (); String Body = NULL; Httpget get = new httpget (url); body = invoke (httpclient, get); httpClient.getConnectionManager (). Shutdown (); corps de retour; } chaîne statique privée Invoke (DefaulthTTPClient httpClient, httpurirequest httppost) {httpResponse réponse = sendRequest (httpClient, httppost); String body = paseResponse (réponse); corps de retour; } private static String PaseResponse (HttpResponse Response) {Httpentity Entity = Response.getEntity (); String charSet = entityUtils.getContentCharset (entité); String Body = NULL; essayez {body = entityutils.toString (entité); } catch (parseException e) {e.printStackTrace (); } catch (ioException e) {e.printStackTrace (); } Retour corps; } private statique httpResponse SendRequest (DefaulthTTPClient httppClient, httpuriRequest httppost) {httpResponse réponse = null; essayez {réponse = httpclient.execute (httpost); } catch (clientProtoCoLexception e) {e.printStackTrace (); } catch (ioException e) {e.printStackTrace (); } Retour Response; } private static httppost postform (string url, map <string, string> params) {httppost httppost = new httppost (url); List <nameValuepair> nvps = new ArrayList <NameValuepair> (); Set <string> keyset = params.KeySet (); for (String key: keyset) {nvps.add (new BasicNameValuepair (key, params.get (key))); } essayez {http.sentity (new UrLencodedFormentity (nvps, http.utf_8)); } catch (UnportEnCcodingException e) {e.printStackTrace (); } return http; } public static void main (string [] args) {// get access_token map <string, string> params = new hashmap <string, string> (); Params.put ("Corpid", "WX5F24FA0DB1819EA2"); Params.put ("CorpSecret", "UQTWZF0BQTL2KRHX0AMEKJPQ8L0AO96LSPSNFCTOBLRBUPO4DUBHMN0_V2JHS-9"); String xml = httpxmlclient.post ("https://qyapi.weixin.qq.com/cgi-bin/gettoken", params); JSONObject JSONMAP = JSONObject.FromObject (xml); Map <string, string> map = new hashmap <string, string> (); Iterator <string> it = jsonmap.keys (); while (it.hasnext ()) {string key = (string) it.next (); String u = jsonmap.get (key) .toString (); map.put (key, u); } String Access_token = map.get ("Access_token"); System.out.println ("Access_token =" + Access_token); // Get Ticket Params.put ("Access_token", Access_token); xml = httpxmlclient.post ("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket", params); JSONMAP = JSONObject.FromObject (xml); map = new HashMap <String, String> (); it = jsonMap.Keys (); while (it.hasnext ()) {string key = (string) it.next (); String u = jsonmap.get (key) .toString (); map.put (key, u); } String jsapi_ticket = map.get ("ticket"); System.out.println ("jsapi_ticket =" + jsapi_ticket); // Get Signature Signature String nonCestr = uUid.randomuuid (). ToString (); String TimeStamp = long.ToString (System.CurrentTimeMillis () / 1000); String url = "http://mp.weixin.qq.com"; String str = "JSAPI_TICKET =" + JSAPI_TICKET + "& nonCestr =" + NonCestr + "× Tamp =" + TimeStamp + "& url =" + url; // SHA1 Signature de chaîne de chiffrement = SHA1 (STR); System.out.println ("NONCESTR =" + NONCESTR); System.out.println ("TimeStamp =" + TimeStamp); System.out.println ("signature =" + signature); // Enfin, Noncestr, horodatage, signature requise pour appeler la vérification de l'interface WeChat JS} / ** * @Author: Luo GuoHUi * @Date: 17 décembre 2015 à 9:24:43 AM * @Description: Sha, SHA1 Encryption * @paramètre: STR: String à être encrypted * @return: Incryption String ** / Public Static String Sha1 (String STR) essayez {messagediGest digest = java.security.MessagediGest .getInstance ("sha-1"); // S'il s'agit de cryptage SHA, changez simplement "sha-1" en "sha" pour digérer.update (str.getbytes ()); BYTE MessagediGest [] = digest.digest (); // Créer une chaîne hexagonale stringbuffer hexstr = new StringBuffer (); // Convertir le tableau d'octets en numéro hexadécimal pour (int i = 0; i <messagediGest.length; i ++) {String shahex = Integer.tohexString (MessagediGest [i] & 0xff); if (shahex.length () <2) {hexstr.append (0); } hexstr.append (shahex); } return hexstr.toString (); } catch (NosuchalgorithMexception e) {e.printStackTrace (); } return null; }}5. Téléchargement du projet
Obtenez un projet de signature sur WeChat
Pour un contenu plus excitant, veuillez cliquer sur "Résumé du didacticiel Android WeChat Development" et "Java WeChat Development Tutorial Résumé" Bienvenue à tout le monde pour apprendre et lire.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.