下面是以快递鸟提供的开发者接口进行展开,如有错误,请指正并及时修改。
首先,申请一个快递鸟的账号;
然后进入http://www.kdniao.com/reg界面点击免费申请,免费申请的接口每天接口的请求次数都是没有限制的,超过3000次/每天需接入订阅推送接口。
按照申请流程一步步做完后,即可对接。
注册信息必须填写正确,如果有误可能导致接口无法正常使用。
使用
案例分为3个
使用的是Chrome的postman插件进行Api测试调用
使用JAVA环境进行快递查询
使用.net环境进行快递查询
打开http://www.kdniao.com/api-track查看Api接口定义文档,了解url、请求参数及响应数据。
主要对即时查询API进行讲解测试.
请求地址:http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx
请求系统级参数说明
参数名称 | 类型 | 说明 | 必须要求 |
---|---|---|---|
RequestData | String | 请求内容需进行URL(utf-8)编码。请求内容JSON或XML格式,须和DataType一致。 | R |
EBusinessID | String | 商户ID,请在我的服务页面查看。 | R |
RequestType | String | 请求指令类型:1002 | R |
DataSign | String | 数据内容签名:把(请求内容(未编码)+AppKey)进行MD5加密,然后Base64编码,最后进行URL(utf-8)编码。详细过程请查看Demo。 | R |
DataType | String | 请求、返回数据类型:1-xml,2-json;默认为xml格式 | O |
备注:R-必填(Required),O-可选(Optional),C-报文中该参数在一定条件下可选(Conditional)。
接口参数
请求内容字段定义
参数 | 类型 | 说明 | 必须要求 |
---|---|---|---|
OrderCode | String | 订单编号 | O |
ShipperCode | String | 快递公司编码 | R |
LogisticCode | String | 物流单号 | R |
返回参数定义
参数名称 | 类型 | 说明 | 必须要求 | |
---|---|---|---|---|
EBusinessID | String | 用户ID | R | |
OrderCode | String | 订单编号 | O | |
ShipperCode | String | 快递公司编码 | R | |
LogisticCode | String | 物流运单号 | R | |
Success | Bool | 成功与否 | R | |
Reason | String | 失败原因 | O | |
State | String | 物流状态:2-在途中,3-签收,4-问题件 | R | |
Traces | ||||
Trace | AcceptTime | String | 时间 | R |
AcceptStation | String | 描述 | R | |
Remark | String | 备注 | O |
使用postman查询
填写请求url及请求参数,下方就是响应的数据,看效果:
使用JAVA环境进行快递查询
package kdniaoApiDemo; 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; /** * * 快递鸟物流轨迹即时查询接口 * * @技术QQ群: 456320272 * @see: http://www.kdniao.com/YundanChaxunAPI.aspx * @copyright: 深圳市快金数据技术服务有限公司 * * DEMO中的电商ID与私钥仅限测试使用,正式环境请单独注册账号 * 单日超过500单查询量,建议接入我方物流轨迹订阅推送接口 * * ID和Key请到官网申请:http://www.kdniao.com/ServiceApply.aspx */ public class kdniaoTrackQueryAPI { //电商ID private String EBusinessID="ID请到官网申请:http://www.kdniao.com/ServiceApply.aspx"; //电商加密私钥,快递鸟提供,注意保管,不要泄漏 private String AppKey="Key请到官网申请:http://www.kdniao.com/ServiceApply.aspx"; //请求url private String ReqURL="http://112.74.108.55/Ebusiness/EbusinessOrderHandle.aspx"; public static void main(String[] args) { // TODO Auto-generated method stub kdniaoTrackQueryAPI api = new kdniaoTrackQueryAPI(); try { String result = api.getOrderTracesByJson("ZTO", "404461891208"); System.out.print(result); } catch (Exception e) { e.printStackTrace(); } } /** * Json方式 查询订单物流轨迹 * @throws Exception */ public String getOrderTracesByJson(String expCode, String expNo) throws Exception{ String requestData= "{‘OrderCode‘:‘‘,‘ShipperCode‘:‘" + expCode + "‘,‘LogisticCode‘:‘" + expNo + "‘}"; Map<String, String> params = new HashMap<String, String>(); params.put("RequestData", urlEncoder(requestData, "UTF-8")); params.put("EBusinessID", EBusinessID); params.put("RequestType", "1002"); 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; } /** * XML方式 查询订单物流轨迹 * @throws Exception */ public String getOrderTracesByXml() throws Exception{ String requestData= "<?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>(); params.put("RequestData", urlEncoder(requestData, "UTF-8")); params.put("EBusinessID", EBusinessID); params.put("RequestType", "1002"); String dataSign=encrypt(requestData, AppKey, "UTF-8"); params.put("DataSign", urlEncoder(dataSign, "UTF-8")); params.put("DataType", "1"); 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 = 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; } /** * 电商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.setRequestProperty("kdniao-nocache", "true"); 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(); } 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(); } }
结果如图所示:
使用.net环境进行快递查询
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.XPath; namespace Track { class Program { static void Main(string[] args) { string result = t.getOrderTracesByJson(args[1], args[0]); Console.WriteLine(result); } public class KdApiSearchDemo { //电商ID private string EBusinessID = "ID请到官网申请:http://www.kdniao.com/ServiceApply.aspx"; //电商加密私钥,快递鸟提供,注意保管,不要泄漏 private string AppKey = "Key请到官网申请:http://www.kdniao.com/ServiceApply.aspx"; //请求url public string ReqURL = "http://120.24.74.29/Ebusiness/EbusinessOrderHandle.aspx"; /// <summary> /// Json方式 查询订单物流轨迹 /// </summary> /// <returns></returns> public string getOrderTracesByJson(string logisticsCode, string expCode) { string requestData = "{‘OrderCode‘:‘‘,‘ShipperCode‘:‘" + expCode + "‘,‘LogisticCode‘:‘" + logisticsCode + "‘}"; Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8)); param.Add("EBusinessID", EBusinessID); param.Add("RequestType", "1002"); 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> /// XML方式 查询订单物流轨迹 /// </summary> /// <returns></returns> public string getOrderTracesByXml(string expCode, string logisticsCode) { string requestData = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<Content>" + "<OrderCode></OrderCode>" + "<ShipperCode>" + expCode + "</ShipperCode>" + "<LogisticCode>" + logisticsCode + "</LogisticCode>" + "</Content>"; Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8)); param.Add("EBusinessID", EBusinessID); param.Add("RequestType", "1002"); string dataSign = encrypt(requestData, AppKey, "UTF-8"); param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8)); param.Add("DataType", "1"); 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)); } } } }
时间: 2024-10-16 12:45:26