How to get a signature using java in WeChat development

Source: Internet
Author: User
Tags sha1 encryption
This article describes how to use java to obtain the signature. if you are interested, refer to this article for details about how to use java to obtain the signature, for more information, see

I. Preface

Three parameters noncestr, timestamp, and signature are required for interface call verification:

The technologies used in this article are HttpClient, Json string to map, and sha1 encryption

II. jar packages to be used

Maven dependent packages include:

1. HttpClient package dependency

  
  
   org.apache.httpcomponents
   httpcore 
  
   4.4.3
  
 
  
  
   org.apache.httpcomponents
   httpclient 
  
   4.5.1
  
 

2. dependencies of json-to-map related packages

     
  
   net.sf.json-lib
      json-lib    
  
   2.4
     
  
   jdk15
   
 
   
  
   xom
    xom  
  
   1.2.5
  
 

III. running results

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. util. iterator; import 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. 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
 
  
Params) {DefaultHttpClient httpclient = new DefaultHttpClient (); String body = null; HttpPost post = postForm (url, params); body = invoke (httpclient, post); httpclient. getConnectionManager (). shutdown (); return body;} 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 (); return body;} private static String invoke (DefaultHttpClient httpclient, HttpUriRequest httpost) {HttpResponse response = sendRequest (httpclient, httpost); String body = paseResponse (response ); return body;} private static String paseResponse (HttpResponse response) {HttpEntity entity = response. getEntity (); String charset = EntityUtils. getContentCharSet (entity); String body = null; try {body = EntityUtils. toString (entity);} catch (ParseException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return body;} private static HttpResponse sendRequest (DefaultHttpClient httpclient, HttpUriRequest httpost) {HttpResponse response = null; try {response = httpclient.exe cute (httpost );} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return response;} private static HttpPost postForm (String url, Map
  
   
Params) {HttpPost httpost = new HttpPost (url); List
   
    
Nvps = new ArrayList
    
     
(); Set
     
      
KeySet = params. keySet (); for (String key: keySet) {nvps. add (new BasicNameValuePair (key, params. get (key);} try {httpost. setEntity (new UrlEncodedFormEntity (nvps, HTTP. UTF_8);} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return httpost;} public static void main (String [] args) {// get access_token Map
      
        Params = new HashMap
       
         (); Params. put ("corpid", "wx5f24fa0db1819ea2"); params. put ("Cortana Cret", "uQtWzF0bQtl2KRHX0amekjpq8L0aO96LSpSNfctOBLRbuYPO4DUBhMn0_v2jHS-9"); String xml = HttpXmlClient. post ("https://qyapi.weixin.qq.com/cgi-bin/gettoken", params); JSONObject jsonMap = JSONObject. fromObject (xml); Map
        
          Map = new HashMap
         
           (); Iterator
          
            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
           
             (); 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); // obtain the 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 +" & timestamp = "+ timestamp +" & url = "+ url; // sha1 encrypted String signature = SHA1 (str); System. out. println ("noncestr =" + noncestr); System. out. println ("timestamp =" + timestamp); System. out. println ("signature =" + signature); // finally obtain the three parameters noncestr, timestamp, signature}/*** @ author required to call the js interface verification: luo Guohui * @ date: 9:24:43 am, December 3, December 17, 2015 * @ description: SHA, SHA1 encryption * @ parameter: str: string to be encrypted * @ return: encrypted String **/public static String SHA1 (String str) {try {MessageDigest digest = java. security. messageDigest. getInstance ("SHA-1"); // For SHA encryption, you only need to change "SHA-1" to "SHA" to digest. update (str. getBytes (); byte messageDigest [] = digest. digest (); // Create Hex String StringBuffer hexStr = new StringBuffer (); // converts a byte array to a hexadecimal number for (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 ;}}
           
          
         
        
       
      
     
    
   
  
 

The preceding section describes how to use java to obtain the signature image and text. For more information, see other related articles on php Chinese network!

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.