春风和煦 - 云代码空间
——
快递查询接口目前对接需求量较大,现在整理一下常用的免费快递查询接口,并附上调用案例,如果有觉得不对的地方,望能够一起沟通探讨!
一.快递查询接口
目前有提供免费快递查询接口的公司有:
快递鸟
快递100
快递网
爱快递
其中快递100和爱快递可以免费查询2000次/每天,快递网可以免费查询500次/每天,而快递鸟接口每天请求次数都是没有限制的,没有超过3000次/每天的可以接入即时查询接口,超过3000次/每天可以免费接入快递鸟订阅推送接口。除了全免费以外,快递鸟也没有必须添加外链的要求。具体的情况可以到各个接口的官网去查看。
二.申请对接
以快递鸟提供的即时查询Api接口进行对接说明:
1.申请一个快递鸟的账号,进入http://www.kdniao.com/reg界面点击免费申请
2.申请完成后即可获得自己的KEY和ID,技术对接完成则可以正常使用
3.注册信息必须填写正确,如果有误可能导致接口无法正常使用
三.调用案例
主要对即时查询API进行讲解测试:
使用的是Chrome的postman插件进行Api测试调用
在JAVA环境下调用
在.net环境下调用
1.接口描述及对接说明
1)打开http://www.kdniao.com/api-track查看Api接口定义文档,了解url、请求参数及响应数据。
2)API 所支持的快递公司及编码
3)请求地址:http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx
2.请求系统级参数说明
参数名称 | 类型 | 说明 | 必须要求 |
---|---|---|---|
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 |
参数 | 类型 | 说明 | 必须要求 |
---|---|---|---|
OrderCode | String | 订单编号 | O |
ShipperCode | String | 快递公司编码 | R |
LogisticCode | String | 物流单号 | R |
2)返回参数定义
参数名称 | 类型 | 说明 | 必须要求 | |
---|---|---|---|---|
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 |
4.调用及图例
1)postman插件进行Api测试调用
<?php //电商ID defined('EBusinessID') or define('EBusinessID', '请到快递鸟官网申请 http://www.kdniao.com/ServiceApply.aspx'); //电商加密私钥,快递鸟提供,注意保管,不要泄漏 defined('AppKey') or define('AppKey', '请到快递鸟官网申请 http://www.kdniao.com/ServiceApply.aspx'); //请求url defined('ReqURL') or define('ReqURL', 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx'); //调用获取物流轨迹 //------------------------------------------------------------- $logisticResult = getOrderTracesByJson('STO', '3308083691559'); echo $logisticResult; //------------------------------------------------------------- /** * Json方式 查询订单物流轨迹 */ function getOrderTracesByJson($shipperCode, $logisticCode){ $requestData= "{\"OrderCode\":\"\",\"ShipperCode\":\"". $shipperCode."\",\"LogisticCode\":\"".$logisticCode."\"}"; $datas = array( 'EBusinessID' => EBusinessID, 'RequestType' => '1002', 'RequestData' => urlencode($requestData) , 'DataType' => '2', ); $datas['DataSign'] = encrypt($requestData, AppKey); $result=sendPost(ReqURL, $datas); //根据公司业务处理返回的信息...... return $result; } /** * XML方式 查询订单物流轨迹 */ function getOrderTracesByXml(){ $requestData= "<?xml version=\"1.0\" encoding=\"utf-8\" ?>". "<Content>". "<OrderCode></OrderCode>". "<ShipperCode>SF</ShipperCode>". "<LogisticCode>589707398027</LogisticCode>". "</Content>"; $datas = array( 'EBusinessID' => EBusinessID, 'RequestType' => '1002', 'RequestData' => urlencode($requestData) , 'DataType' => '1', ); $datas['DataSign'] = encrypt($requestData, AppKey); $result=sendPost(ReqURL, $datas); //根据公司业务处理返回的信息...... return $result; } /** * post提交数据 * @param string $url 请求Url * @param array $datas 提交的数据 * @return url响应返回的html */ function sendPost($url, $datas) { $temps = array(); foreach ($datas as $key => $value) { $temps[] = sprintf('%s=%s', $key, $value); } $post_data = implode('&', $temps); $url_info = parse_url($url); $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n"; $httpheader.= "Host:" . $url_info['host'] . "\r\n"; $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n"; $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n"; $httpheader.= "Connection:close\r\n\r\n"; $httpheader.= $post_data; $fd = fsockopen($url_info['host'], 80); fwrite($fd, $httpheader); $gets = ""; $headerFlag = true; while (!feof($fd)) { if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) { break; } } while (!feof($fd)) { $gets.= fread($fd, 128); } fclose($fd); return $gets; } /** * 电商Sign签名生成 * @param data 内容 * @param appkey Appkey * @return DataSign签名 */ function encrypt($data, $appkey) { return urlencode(base64_encode(md5($data.$appkey))); } ?>
2)在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(); } }
调试结果如图所示:
3)在.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)); } } } }