1. Prefácio
Os três parâmetros que são usados em última análise para a verificação de chamadas da interface do WeChat:
Em seguida, o código detalhado para obter esses três parâmetros será fornecido. O ambiente deste artigo é Eclipse + Maven.
As tecnologias usadas neste artigo httpclient, string json para mapear, criptografia sha1
2. O pacote JAR exigido
Os pacotes dos quais o MAVEN depende são:
1. Dependência do pacote httpclient
<Depencency> <PuerpId> org.apache.httpcomponents </groupiD> <TROTIFACTID> httpcore </artifactId> <versão> 4.4.3 </versão </dependency> <spendency> <vurfactId> org.apache.httpomponEnts </proupidId> <strifactId> httpache. <Versão> 4.5.1 </sisters> </dependency>
2. JSON para mapear dependências de pacotes relacionadas
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency><dependency> <groupId>xom</groupId> <artifactId>xom</artifactId> <version>1.2.5</version></dependency>
3. Resultados da operação
4. Código detalhado
pacote com.luo.util; importar java.io.ioException; importar java.io.unsupportEnCodingException; importar java.security.MessagedIgest; importar java.Security.NosuchalGorithMexception; import.util.arrayList; importação; java.util.list; importar java.util.map; importar java.util.set; importar java.util.uuid; importar net.sf.json.jsonObject; import org.apache.httpp.httpentity 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.HttpPost;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.entityUtils; public class HttpxmlClient {public static string post (string url, map <string, string> params) {defaultTttpClient httpclient = new DefaultTtpClient (); Corpo de corda = nulo; Httppost post = pós -forma (url, params); corpo = invocar (httpclient, post); httpclient.getConnectionManager (). Shutdown (); corpo de retorno; } public static string get (string url) {defaulthttpClient httpClient = new DefaultTtpClient (); Corpo de corda = nulo; Httpget get = novo httpget (url); corpo = invocar (httpclient, get); httpclient.getConnectionManager (). Shutdown (); corpo de retorno; } String estática privada Invoke (DefaultTtpClient httpClient, httpurirequest httpPost) {httproponse Response = sendRequest (httpClient, httppost); Corpo de corda = PASEResponse (resposta); corpo de retorno; } String estática privada PASERESPONSE (HTTPRESPOnsion) {entidade httPentity = Response.getEntity (); String charset = entityutils.getContentCharset (entidade); Corpo de corda = nulo; tente {body = entityutils.toString (entidade); } catch (parseException e) {e.printStackTrace (); } catch (ioexception e) {e.printStackTrace (); } retornar corpo; } private estático httpResponse sendRequest (DefaultTttpClient httppclient, httpurirequest httppost) {httproponse resposta = null; tente {resposta = httpclient.execute (httpost); } catch (clientprotocolexception e) {e.printStackTrace (); } catch (ioexception e) {e.printStackTrace (); } resposta de retorno; } private estático httppost PostForm (String url, map <string, string> params) {httppost httppost = new httppost (url); Lista <NameValuepair> nvps = new ArrayList <NameValuepair> (); Set <string> keyset = params.keyset (); para (String Key: Keyset) {nvps.add (new BasicNameValuepair (Key, Params.get (Key))); } tente {http.setEntity (new urlencodedFormentity (nvps, http.utf_8)); } Catch (UnsupportEdEncodingException e) {E.PrintStackTrace (); } retornar 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", "uqtwzf0bqtl2krhx0amekjpq8l0ao96lspsnfctoblrbuypo4dubhmn0_v2jhs-9"); String xml = httpxmlclient.post ("https://qyapi.weixin.qq.com/cgi-bin/gettoken", params); JsonObject jsonmap = jsonObject.FromObject (xml); Mapa <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 (chave, 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 = novo hashmap <string, string> (); it = jsonmap.keys (); while (it.hasnext ()) {string key = (string) it.next (); String u = jsonmap.get (key) .toString (); map.put (chave, u); } String jsapi_ticket = map.get ("ticket"); System.out.println ("jsapi_ticket =" + jsapi_ticket); // Obtenha string de assinatura de assinatura noncestr = uuid.randomuuid (). ToString (); Timestamp String = Long.toString (System.CurrentTimemillis () / 1000); String url = "http://mp.weixin.qq.com"; String str = "jsapi_ticket =" + jsapi_ticket + "& noncestr =" + noncest + "× tamp =" + timestamp + "& url =" + url; // sha1 de criptografia String assinatura = sha1 (str); System.out.println ("noncestr =" + não -cest); System.out.println ("timestamp =" + timestamp); System.out.println ("Signature =" + Signature); // Finalmente, não -cesto, registro de data e hora, necessária para chamar WeChat JS Interface Verification}/*** @Author: Luo guohui* @Date: 17 de dezembro de 2015 às 9:24:43 String* @Description: sha, shaTtion* @parameter: string a senção* @Descript* str) {tente {Messagedigest Digest = java.Security.Messagedigest .GetInstance ("sha-1"); // Se for criptografia sha, basta alterar "sha-1" para "sha" para diger.update (str.getBytes ()); byte Messagedigest [] = DIGEST.Digest (); // Crie String String HexBuffer hexstr = new StringBuffer (); // Converta a matriz de bytes em número hexadecimal para (int i = 0; i <Messagedigest.Length; i ++) {String Shahex = Integer.ToHexString (Messagedigest [i] e 0xff); if (shahex.length () <2) {hexstr.append (0); } hexstr.append (shahex); } retornar hexstr.toString (); } catch (nosuchalgorithMexception e) {e.printStackTrace (); } retornar nulo; }}5. Download do projeto
Obtenha um projeto de assinatura no WeChat
Para um conteúdo mais emocionante, clique em "Resumo do tutorial de desenvolvimento do Android WeChat" e "Java WeChat Development Tutorial Resumo" Dê as boas -vindas a todos para aprender e ler.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.