電子面單介面申請對接(返回電子面單模板)
阿新 • • 發佈:2019-02-02
介面支援的訊息接收方式:HTTPPOST
請求方法的編碼格式(utf-8):"application/x-www-form-urlencoded;charset=utf-8"
請求、返回資料型別:只支援JSON格式
介面提供:快遞鳥
(JAVA對接原始碼)
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.util.HashMap; import java.util.Map; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import java.security.MessageDigest; /** * * 快遞鳥電子面單介面 * */ public class KdGoldAPIDemo { //電商ID private String EBusinessID="請到快遞鳥官網申請http://www.kdniao.com/ServiceApply.aspx"; //電商加密私鑰,快遞鳥提供,注意保管,不要洩漏 private String AppKey="請到快遞鳥官網申請http://www.kdniao.com/ServiceApply.aspx"; //請求url, 正式環境地址:http://api.kdniao.cc/api/Eorderservice private String ReqURL="http://testapi.kdniao.cc:8081/api/Eorderservice"; /** * Json方式 電子面單 * @throws Exception */ public String orderOnlineByJson() throws Exception{ String requestData= "{'OrderCode': '012657700387'," + "'ShipperCode':'EMS'," + "'PayType':1," + "'ExpType':1," + "'Cost':1.0," + "'OtherCost':1.0," + "'Sender':" + "{" + "'Company':'LV','Name':'Taylor','Mobile':'15018442396','ProvinceName':'上 海','CityName':'上海','ExpAreaName':'青浦區','Address':'明珠路73號'}," + "'Receiver':" + "{" + "'Company':'GCCUI','Name':'Yann','Mobile':'15018442396','ProvinceName':'北 京','CityName':'北京','ExpAreaName':'朝陽區','Address':'三里屯街道雅秀大廈'}," + "'Commodity':" + "[{" + "'GoodsName':'鞋子','Goodsquantity':1,'GoodsWeight':1.0}]," + "'Weight':1.0," + "'Quantity':1," + "'Volume':0.0," + "'Remark':'小心輕放'," + "'IsReturnPrintTemplate':1}"; Map<String, String> params = new HashMap<String, String>(); params.put("RequestData", urlEncoder(requestData, "UTF-8")); params.put("EBusinessID", EBusinessID); params.put("RequestType", "1007"); String dataSign=encrypt(requestData, AppKey, "UTF-8"); params.put("DataSign", urlEncoder(dataSign, "UTF-8")); params.put("DataType", "2"); String result=sendPost(ReqURL, params); //根據公司業務處理返回的資訊...... return result; } /** * MD5加密 * @param str 內容 * @param charset 編碼方式 * @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編碼 * @param str 內容 * @param charset 編碼方式 * @throws UnsupportedEncodingException */ private String base64(String str, String charset) throws UnsupportedEncodingException{ String encoded = Base64.encode(str.getBytes(charset)); return encoded; } @SuppressWarnings("unused") private String urlEncoder(String str, String charset) throws UnsupportedEncodingException{ String result = URLEncoder.encode(str, charset); return result; } /** * 電商Sign簽名生成 * @param content 內容 * @param keyValue Appkey * @param charset 編碼方式 * @throws UnsupportedEncodingException ,Exception * @return DataSign簽名 */ @SuppressWarnings("unused") private String encrypt (String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception { if (keyValue != null) { return base64(MD5(content + keyValue, charset), charset); } return base64(MD5(content, charset), charset); } /** * 向指定 URL 傳送POST方法的請求 * @param url 傳送請求的 URL * @param params 請求的引數集合 * @return 遠端資源的響應結果 */ @SuppressWarnings("unused") private String sendPost(String url, Map<String, String> params) { OutputStreamWriter out = null; BufferedReader in = null; StringBuilder result = new StringBuilder(); try { URL realUrl = new URL(url); HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection(); // 傳送POST請求必須設定如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // POST方法 conn.setRequestMethod("POST"); // 設定通用的請求屬性 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(); // 獲取URLConnection物件對應的輸出流 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 傳送請求引數 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輸出流的緩衝 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } //使用finally塊來關閉輸出流、輸入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result.toString(); } }
(C#對接原始碼)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace KdGoldAPI { /** * * 快遞鳥電子面單介面 * */ public class KdApiEOrderDemo { //電商ID private string EBusinessID = "請到快遞鳥官網申請http://www.kdniao.com/ServiceApply.aspx"; //電商加密私鑰,快遞鳥提供,注意保管,不要洩漏 private string AppKey = "請到快遞鳥官網申請http://www.kdniao.com/ServiceApply.aspx"; //請求url, 正式環境地址:http://api.kdniao.cc/api/Eorderservice private string ReqURL = "http://testapi.kdniao.cc:8081/api/EOrderService"; /// <summary> /// Json方式 電子面單 /// </summary> /// <returns></returns> public string orderTracesSubByJson() { string requestData = "{'OrderCode': '012657700312'," + "'ShipperCode':'YTO'," + "'PayType':1," + "'ExpType':1," + "'Cost':1.0," + "'OtherCost':1.0," + "'Sender':" + "{" + "'Company':'LV','Name':'Taylor','Mobile':'15018442396','ProvinceName':'上海','CityName':'上海','ExpAreaName':'青浦區','Address':'明珠路73號'}," + "'Receiver':" + "{" + "'Company':'GCCUI','Name':'Yann','Mobile':'15018442396','ProvinceName':'北京','CityName':'北京','ExpAreaName':'朝陽區','Address':'三里屯街道雅秀大廈'}," + "'Commodity':" + "[{" + "'GoodsName':'鞋子','Goodsquantity':1,'GoodsWeight':1.0}]," + "'AddService':" + "[{" + "'Name':'COD','Value':'1020'}]," + "'Weight':1.0," + "'Quantity':1," + "'Volume':0.0," + "'Remark':'小心輕放'," + "'IsReturnPrintTemplate':1}"; Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8)); param.Add("EBusinessID", EBusinessID); param.Add("RequestType", "1007"); string dataSign = encrypt(requestData, AppKey, "UTF-8"); param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8)); param.Add("DataType", "2"); string result = sendPost(ReqURL, param); //根據公司業務處理返回的資訊...... return result; } /// <summary> /// Post方式提交資料,返回網頁的原始碼 /// </summary> /// <param name="url">傳送請求的 URL</param> /// <param name="param">請求的引數集合</param> /// <returns>遠端資源的響應結果</returns> private string sendPost(string url, Dictionary<string, string> param) { string result = ""; StringBuilder postData = new StringBuilder(); if (param != null && param.Count > 0) { foreach (var p in param) { if (postData.Length > 0) { postData.Append("&"); } postData.Append(p.Key); postData.Append("="); postData.Append(p.Value); } } byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString()); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "application/x-www-form-urlencoded"; request.Referer = url; request.Accept = "*/*"; request.Timeout = 30 * 1000; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; request.Method = "POST"; request.ContentLength = byteData.Length; Stream stream = request.GetRequestStream(); stream.Write(byteData, 0, byteData.Length); stream.Flush(); stream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream backStream = response.GetResponseStream(); StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8")); result = sr.ReadToEnd(); sr.Close(); backStream.Close(); response.Close(); request.Abort(); } catch (Exception ex) { result = ex.Message; } return result; } ///<summary> ///電商Sign簽名 ///</summary> ///<param name="content">內容</param> ///<param name="keyValue">Appkey</param> ///<param name="charset">URL編碼 </param> ///<returns>DataSign簽名</returns> private string encrypt(String content, String keyValue, String charset) { if (keyValue != null) { return base64(MD5(content + keyValue, charset), charset); } return base64(MD5(content, charset), charset); } ///<summary> /// 字串MD5加密 ///</summary> ///<param name="str">要加密的字串</param> ///<param name="charset">編碼方式</param> ///<returns>密文</returns> private string MD5(string str, string charset) { byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str); try { System.Security.Cryptography.MD5CryptoServiceProvider check; check = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] somme = check.ComputeHash(buffer); string ret = ""; foreach (byte a in somme) { if (a < 16) ret += "0" + a.ToString("X"); else ret += a.ToString("X"); } return ret.ToLower(); } catch { throw; } } /// <summary> /// base64編碼 /// </summary> /// <param name="str">內容</param> /// <param name="charset">編碼方式</param> /// <returns></returns> private string base64(String str, String charset) { return Convert.ToBase64String(System.Text.Encoding.GetEncoding(charset).GetBytes(str)); } } }