1. Предисловие
Три параметра, которые в конечном итоге используются для проверки интерфейса WeChat:
Далее будет предоставлен подробный код для получения этих трех параметров. Среда этой статьи - Eclipse + Maven.
Технологии, используемые в этой статье, httpclient, json String to Map, шифрование SHA1
2. Требуемый пакет JAR
Пакеты, от которых зависит Maven, это:
1. Зависимость от пакета HttpClient
<dependency> <groupid> org.apache.httpcomponents </groupid> <artifactid> httpcore </artifactid> <serse> 4.4.3 </version> </dependency> <dehyederiny> <groupid> org.apache.httpcomponents </GroupD> <strifactId> httpclient </ttpcomponents </GroupD> <strifactId> httpclient </artifactid> </artifactid> <версия> 4.5.1 </version> </depertive>
2. JSON для карты зависимостей, связанных с пакетом,
<depervice> <groupid> net.sf.json-lib </groupid> <artifactid> json-lib </artifactid> <serse> 2.4 </version> <classicifier> jdk15 </classicifier> </repertive> <dependency> <groupid> xom </GroupId> <strifactid> xom </artifactid> <serse> 1.2.
3. Результаты работы
4. Подробный код
пакет com.luo.util; импорт java.io.ioexception; импорт java.io.unsupportedencodingexception; импорт java.security.messagedigest; импорт java.security.nosuchalgorithmexception; импорт java.util.ArrayList; импорт. java.util.list; import java.util.map; import java.util.set; import java.util.uuid; import net.sf.json.jsonobject; импорт org.apache.http.httpentity; импорт org.apache.http.httpresponse; org.apache.http.parseexception; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.Entity.UrlencodedFormentity; импорт org.apache.http.client.methods.httpget; org.apache.http.client.methods.httpurirequest; import org.apache.http.impl.client.defaulthttpclient; импорт org.apache.http.message.basicnamevaluepair; импорт org.apache.http.protocol.hattpair; org.apache.http.util.entityutils; открытый класс httpxmlclient {public static String post (string url, map <string> params) {defaulthttpclient httpclient = new DefaulthttpClient (); Строка корпуса = null; Httppost post = postform (url, params); body = invoke (httpclient, post); httpclient.getConnectionManager (). Shutdown (); возвращение тела; } public Static String get (string url) {defaulthttpclient httpclient = new Defaulthttpclient (); Строка корпуса = null; Httpget get = new httpget (url); body = invoke (httpclient, get); httpclient.getConnectionManager (). Shutdown (); возвращение тела; } частная статическая строка Invoke (defaulthttpclient httpclient, httpurirequest httppost) {httpresponse response = sendrequest (httpclient, httppost); Строка Body = paseresponse (ответ); возвращение тела; } частная статическая строка paseresponse (httpresponse response) {httpentity entity = response.getentity (); String charset = entityutils.getContentArset (Entity); Строка корпуса = null; try {body = entityutils.tostring (entity); } catch (parseexception e) {e.printstacktrace (); } catch (ioException e) {e.printstackTrace (); } return Body; } Частный статический httpresponse sendrequest (Defaulthttpclient httppclient, httpurirequest httppost) {httpresponse 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 httppost = new httppost (url); List <mankvaluepair> nvps = new Arraylist <mankvaluepair> (); SET <String> keySet = params.keyset (); for (String Key: Keyset) {nvps.add (new basicnamevaluepair (key, params.get (key))); } try {http.setentity (new urlencodedformentity (nvps, http.utf_8)); } catch (unsupportEncodingexception e) {e.printstacktrace (); } return http; } public static void main (string [] args) {// get access_token map <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); Map <string, string> map = new hashmap <string, string> (); Итератор <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); // получить билет 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); // Получить подпись подписи строки noncest = 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 = SHA1 (STR); System.out.println ("noncestr =" + noncestr); System.out.println ("timeStamp =" + timeStamp); System.out.println ("signature =" + signature); // Наконец, не cestr, timeStamp, подпись, необходимая для вызова проверки интерфейса weChat JS}/*** @author: luo guohui* @date: 17 декабря 2015 г. в 9:24:43* @description: sha, encryption incryption* @parameter: str: string* @return: encryption ** String ** String ** String. {try {messagegest digest = java.security.messagedigest .getinstance ("sha-1"); // Если это шифрование SHA, просто измените «SHA-1» на «sha» на Digest.update (str.getbytes ()); Byte MessageDigest [] = digest.digest (); // Создать шестигранную строку stringbuffer hexstr = new StringBuffer (); // преобразовать байтовые массивы в шестнадцатеричный номер для (int i = 0; i <messagedigest.length; i ++) {string shahex = integer.tohexstring (messagedigest [i] & 0xff); if (shahex.length () <2) {hexstr.append (0); } hexstr.append (shahex); } вернуть hexstr.toString (); } catch (nosuchalgorithmexception e) {e.printstacktrace (); } return null; }}5. Загрузка проекта
Получить подпись проекта на WeChat
Для получения более захватывающего контента, пожалуйста, нажмите «Резюме для разработки Android WeChat» и «Резюме по разработке Java WeChat» Добро пожаловать, чтобы все учились и прочитали.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.