Micro-credit development using Java to obtain the signature Signature_java

Source: Internet
Author: User

First, the preface

Micro-Interface Call validation the final three parameters to be used noncestr, timestamp, Signature:

Next, we'll give you a detailed code to get these three parameters.
This article's Environment Eclipse + maven
The technology used in this article httpclient, JSON string to map, SHA1 encryption

Second, need to use the jar package

The packages that Maven relies on are:

1, HttpClient package dependence

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactid>httpcore </artifactId>
 <version>4.4.3</version>
</dependency>
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactid>httpclient</artifactid >
 <version>4.5.1</version>
</dependency>

2, JSON to map related package dependencies

<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>

Iii. Results of operation

Four, detailed code

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<string, string> params) {defaulthttpclient httpclient = NE
    W defaulthttpclient ();
    String BODY = null;
    HttpPost post = postform (URL, params);
    BODY = Invoke (httpclient, post);
    Httpclient.getconnectionmanager (). Shutdown ();
  return to 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 to body; private static String Invoke (Defaulthttpclient httpclient, Httpurirequest httpost) {HttpResponse response
    = SendRequest (httpclient, httpost);
    String BODY = paseresponse (response);
  return to 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 to body; private static HttpResponse SendRequest (Defaulthttpclient httpclient, Httpurirequest httpost) {httprespons
    e response = null;
    try {response = Httpclient.execute (httpost);
    catch (Clientprotocolexception e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace ();
  return response; private static HttpPost postform (String URL, map<string, string> params) {HttpPost httpost = 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)); 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<string, string> params = new Hashmap<s
    Tring, 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);
    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);
    Gets the 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 + "&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 get the call to the micro-letter JS Interface validation required three parameters Noncestr, timestamp, signature}
    /** * @author: Rev. Law * @date: December 17, 2015 Morning 9:24:43 * @description: SHA, SHA1 encryption * @parameter: STR: strings to be encrypted * @return: Cryptographic string **/public static string SHA1 (String str) {try {messagedigest digest = Java.security.Mes Sagedigest. getinstance ("SHA-1");
      If it is SHA encryption only need to change "SHA-1" to "Sha" Can be Digest.update (Str.getbytes ());
      byte messagedigest[] = Digest.digest ();
      Create Hex String StringBuffer hexstr = new StringBuffer (); The byte array is converted to a hexadecimal number for (int i = 0; i < messagedigest.length; i++) {String Shahex = integer.tohexstring (Me
        Ssagedigest[i] & 0xFF);
        if (Shahex.length () < 2) {hexstr.append (0);
      } hexstr.append (Shahex);

    return hexstr.tostring ();
    catch (NoSuchAlgorithmException e) {e.printstacktrace ();
  return null;

 }
}

V. Project download

Micro-letter Acquisition Signature project: Http://xiazai.jb51.net/201608/yuanma/javaproject (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.

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.