JAVA Express Query Interface API call-Express Bird interface

Source: Internet
Author: User
Tags base64 finally block md5 encryption

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.unsupportedencodingexception;import Java.net.HttpURLConnection;import Java.net.url;import Java.net.urlencoder;import Java.security.messagedigest;import Java.util.HashMap;import Java.util.Map; /** * * Express Bird Logistics Track Instant Query interface * * Technology QQ Group: 456320272 * @see: http://www.kdniao.com/YundanChaxunAPI.aspx * @copyright: Shenzhen Fast Gold Data Technology Services Limited Company * * e-commerce ID and private key in demo only for test use, official environment please register account separately * More than 500 single queries a day, recommended access to our Logistics track Subscription Push interface * * ID and key Please apply to the official website: http://www.kdniao.com/ Serviceapply.aspx */public class Kdniaotrackqueryapi {//demopublic static void main (string[] args) {Kdniaotrackqueryapi API = new Kdniaotrackqueryapi (); try {String result = Api.getordertracesbyjson ("ANE", "210001633605"); System.out.print (result);} catch (Exception e) {e.printstacktrace ();}} E-commerce idprivate String ebusinessid= "Please apply to express Bird official website http://www.kdniao.com/ServiceApply.aspx";//e-commerce encryption private key, courier birds provided, attention to custody, Do not leak private String appkey= "Please go to the Express Bird official website to apply for http://www.kdniao.com/serviceapply.aspx ";//Request urlprivate String requrl=" http://api.kdniao.cc/Ebusiness/ Ebusinessorderhandle.aspx "; /** * JSON way to Query Order logistics track * @throws Exception */public string Getordertracesbyjson (String Expcode, string expno) thro WS exception{string requestdata= "{' Ordercode ': ', ' shippercode ': '" + Expcode + "', ' logisticcode ': '" + Expno + "'}"; map<string, string> params = new hashmap<string, string> ();p arams.put ("RequestData", Urlencoder ( RequestData, "UTF-8"));p arams.put ("Ebusinessid", Ebusinessid);p arams.put ("RequestType", "1002"); String Datasign=encrypt (RequestData, AppKey, "UTF-8");p arams.put ("Datasign", Urlencoder (Datasign, "UTF-8")); Params.put ("DataType", "2"); String result=sendpost (Requrl, params);//The information returned according to the company's business process ... return result; /** * XML Query Order Logistics track * @throws Exception */public String getordertracesbyxml () throws Exception{string Requestdat A= "<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>" + "<Content>" + "<ordercode></ordercOde> "+" <ShipperCode>SF</ShipperCode> "+" <LogisticCode>589707398027</LogisticCode> "+" </Content> "; map<string, string> params = new hashmap<string, string> ();p arams.put ("RequestData", Urlencoder ( RequestData, "UTF-8"));p arams.put ("Ebusinessid", Ebusinessid);p arams.put ("RequestType", "1002"); String Datasign=encrypt (RequestData, AppKey, "UTF-8");p arams.put ("Datasign", Urlencoder (Datasign, "UTF-8")); Params.put ("DataType", "1"); String result=sendpost (Requrl, params);//The information returned according to the company's business process ... return result; /** * MD5 encryption * @param STR content * @param charset encoding method * @throws Exception */@SuppressWarnings ("unused"     ) Private string MD5 (String str, String charset) throws Exception {MessageDigest MD = messagedigest.getinstance ("MD5");    Md.update (Str.getbytes (charset));    Byte[] result = Md.digest ();    StringBuffer sb = new StringBuffer (32);        for (int i = 0; i < result.length; i++) {int val = result[i] & 0xff; if (VAl <= 0xf) {sb.append ("0");    } sb.append (Integer.tohexstring (Val)); } return Sb.tostring (). toLowerCase ();} /** * Base64 encoding * @param STR content * @param charset encoding * @throws unsupportedencodingexception */priv Ate string base64 (String str, String charset) throws unsupportedencodingexception{string encoded = Base64Encode (    Str.getbytes (CharSet)); return encoded; } @SuppressWarnings ("unused") Private String Urlencoder (String str, String charset) throws Unsupportedencodingexception {String result = Urlencoder.encode (str, charset); return result;} /** * e-commerce sign Signature generation * @param content Contents * @param keyValue Appkey * @param charset encoding method * @throws Unsuppo Rtedencodingexception, Exception * @return datasign Signature */@SuppressWarnings ("unused") private string Encrypt (String cont ENT, String keyValue, String charset) throws Unsupportedencodingexception, Exception{if (keyValue! = null) {return Base64 ( MD5 (content + KeyValue, charset), CharSet);} Return base64 (MD5 (Content, CharSet), CharSet);}      /** * Request to send a POST method to the specified URL * @param URL to send the request * @param params request Parameter Collection * @return The response result of the remote resource */@SuppressWarnings ("unused") Private String sendpost (string url, map<string, string> params) {Outputstr        Eamwriter out = null;                BufferedReader in = null;         StringBuilder result = new StringBuilder ();            try {URL realurl = new URL (URL);            HttpURLConnection conn = (httpurlconnection) realurl.openconnection ();            The Send POST request must be set to the following two lines conn.setdooutput (true);            Conn.setdoinput (TRUE);            Post Method Conn.setrequestmethod ("post");            Set the generic request attribute Conn.setrequestproperty ("accept", "*/*");            Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;            SV1) "); Conn.setrequEstproperty ("Content-type", "application/x-www-form-urlencoded");            Conn.connect ();            Gets the output stream corresponding to the URLConnection object out = new OutputStreamWriter (Conn.getoutputstream (), "UTF-8");           Send request parameter if (params! = null) {StringBuilder param = new StringBuilder (); For (map.entry<string, string> entry:params.entrySet ()) {if (Param.length () >0) {Param.append (          "&");          } param.append (Entry.getkey ());          Param.append ("=");                    Param.append (Entry.getvalue ());          System.out.println (Entry.getkey () + ":" +entry.getvalue ());          }//system.out.println ("Param:" +param.tostring ());            Out.write (Param.tostring ());            }//Flush output stream buffer Out.flush (); Defines the BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (conn.getinput     Stream (), "UTF-8"));       String Line;            while (line = In.readline ())! = null) {result.append (line);        }} catch (Exception e) {e.printstacktrace (); }//Use finally block to close the output stream, input stream finally{try{if (out!=null) {Out.close                ();                } if (In!=null) {in.close ();            }} catch (IOException ex) {ex.printstacktrace ();    }} return result.tostring (); } private static char[] Base64encodechars = new char[] {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' A ', ' B ', ' C ', ' d ', ' e ' ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' X ', ' Y ', ' z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', '+ ', '/'};         public static String Base64Encode (byte[] data) {StringBuffer SB = new StringBuffer ();         int len = data.length;         int i = 0;         int B1, B2, B3;             while (I < len) {B1 = data[i++] & 0xff;                 if (i = = len) {sb.append (base64encodechars[b1 >>> 2]);                 Sb.append (base64encodechars[(B1 & 0x3) << 4]);                 Sb.append ("= =");             Break             } b2 = data[i++] & 0xff;                 if (i = = len) {sb.append (base64encodechars[b1 >>> 2]); Sb.append (base64encodechars[(B1 & 0x03) << 4) |                 ((B2 & 0xf0) >>> 4)]);                 Sb.append (base64encodechars[(B2 & 0x0f) << 2]);                 Sb.append ("=");             Break             } B3 = data[i++] & 0xff;   Sb.append (BASE64ENCODECHARS[B1 >>> 2]);          Sb.append (base64encodechars[(B1 & 0x03) << 4) |             ((B2 & 0xf0) >>> 4)]); Sb.append (base64encodechars[(B2 & 0x0f) << 2) |             ((B3 & 0xc0) >>> 6)]);         Sb.append (Base64encodechars[b3 & 0x3f]);     } return sb.tostring (); }}

  

JAVA Express Query Interface API call-Express Bird interface

Related Article

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.