[Scene demand Description
Electronic business platform and ISV business demand for logistics api interface, there are many, and today we share is the main docking guide birds express courier single query interface number, express a single query interface docking scenarios are many, many scenes encounter, the most important is called when the user opens the electricity supplier website "my orders" this API to display details of logistics information, the electricity supplier logistics system management background, the status of all customer service inquiries sign the waybill before reconciliation, and tracing, electronic business platform to-business logistics management and control requirements must embrace the pieces must be sent to see how long the express condition, to see how long the goods receipt must be received by the state, according to the state of business control and improve overall user satisfaction.
[Butt] using flow
1, register an account and apply for certification birds Express
2, express logistics birds query to track state based on a single number and courier companies
3, the bird will express logistics queries to track back to the state electricity provider platform for service providers or ISV
4, electronic business platform ISV or service provider receives the data and do real-time processing or data presentation applications
Express birds very powerful, free, you can query the express track at any time, you can push the express condition, very powerful very convenient. Direct the implementation code. Code on directly: this is the development of a bird express courier push the interface, the received data processing data. This method must post
@RequestMapping(value = "tuisong",method=RequestMethod.POST)
@ResponseBody
public Map<String,Object> tuisong(String RequestData,String RequestType,String DataSign) {
RequestData=Encodes.unescapeHtml(RequestData);
Map<String,Object> result=new HashMap<String,Object>();
//判断是从快递鸟进入
if(!(RequestType.equals("101") && KdniaoUtils.isFromKdniao(RequestData, DataSign))){
result.put("Success",false);
result.put("Reason","不是快递鸟推送来的数据。");
return result;
}
JSONObject jsonObj=new JSONObject(RequestData);
result.put("EBusinessID",jsonObj.getString("EBusinessID"));
result.put("UpdateTime",jsonObj.getString("PushTime"));
try {
JSONArray jsonArray=jsonObj.getJSONArray("Data");
List<Ship> shipList=Lists.newArrayList();
Ship ship=null;
for(int i=0;i<jsonArray.length();i++){
jsonObj=jsonArray.getJSONObject(i);
if(!jsonObj.getBoolean("Success")){
continue;
}
ship=new Ship();
ship.setExpress(ErpUtils.getExpressByKdniao(jsonObj.getString("ShipperCode")));
ship.setExpressNo(jsonObj.getString("LogisticCode"));
String state=jsonObj.getString("State");
ship.setStatus(KdniaoUtils.getShipStatus(state));
if(ship.getStatus().equals(Ship.STATUS_SIGN)){
JSONArray array=jsonObj.getJSONArray("Traces");
JSONObject obj=array.getJSONObject(array.length()-1);
String time=obj.getString("AcceptTime");
ship.setSignTime(DateUtils.parseDate(time,"yyyy-MM-dd HH:mm:ss"));
}
shipList.add(ship);
}
shipService.updateStatus(shipList);
result.put("Success", true);
}catch (Exception e) {
result.put("Success", false);
result.put("Reason ", "解析数据失败。");
e.printStackTrace();
}
return result;
Here is a utility class provides static methods. KdniaoUtils.java
`` public class KdniaoUtils {
// the DEMO
public static void main (String [] args) throws UnsupportedEncodingException, Exception {
}
// electricity supplier ID
Private EBusinessID static String = "1283391";
// private key encryption electricity supplier, express offers a bird, take good care not to leak
Private AppKey static String = "9df9507a-62fa-47f3-9227-bdd02b95ccf1";
// request url
Private reqURL static String = " http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle. ASPX ";
public static the Map <String, String> = new new StateMap the HashMap <String, String> ();
static {
StateMap.put (" 0 "," no record ");
StateMap.put (". 1 "," football has income ");
StateMap.put (" 2 "," transit ");
StateMap.put ( "3", "have been received");
StateMap.put ( ". 4", "Problems member");
}
// stream Status: 0-no trace, 1-Lanshou, 2-way 201 - sending pieces arrival city, sign 3-, 4- problems pieces
public static int getShipStatus (String State) {
Switch (State) {
Case "0":
return Ship.STATUS_SHIPPED;
Case ". 1":
return Ship.STATUS_SHIPPED;
Case " 2 ":
return Ship.STATUS_ONTHEWAY;
Case" 201 ":
return Ship.STATUS_PAISONG;
Case". 3 ":
return Ship.STATUS_SIGN;
Case". 4 ":
return Ship.STATUS_DIFFICULT;
default:
return Ship.STATUS_SHIPPED;
}
}
/ **
- Express logistics tracking
- @param ship
- @return
*/
public static Map<String, Object> trace(Ship ship){
Map<String, Object> map = new HashMap<String, Object>();
try {
String result=getOrderTracesByJson(ship.getExpress().getKdniao(),ship.getExpressNo());
JSONObject dataJson = new JSONObject(result);
if(dataJson.getBoolean("Success")){
map.put("errCode",0);
String state=dataJson.getString("state");
map.put("status",getShipStatus(state));
map.put("statusName",StateMap.containsKey(state)?StateMap.get(state):state);
JSONArray list = (JSONArray) dataJson.get("Traces");
if(list!=null&&list.length()>0) {
List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
for (int i = 0; i < list.length(); i++) {
JSONObject dataMapJson = (JSONObject) list.get(i);
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("time", dataMapJson.getString("AcceptTime"));// 每条跟踪信息的时间
dataMap.put("content", dataMapJson.getString("AcceptStation"));// 每条跟综信息的描述
dataList.add(dataMap);
}
map.put("dataList", dataList);
}
}else{
map.put("errCode",1);
map.put("errMsg", dataJson.getString("Reason"));
}
} catch (Exception e) {
map.put("errMsg","快递接口调用出错。");
e.printStackTrace();
}
return map;
}
/** - 发送订阅信息
*/
public static Map<String, Object> subscribe(Ship ship){
Map<String, Object> map = new HashMap<String, Object>();
try {
String result=orderTracesSubByJson(ship.getExpress().getKdniao(),ship.getExpressNo());
JSONObject dataJson = new JSONObject(result);
if(dataJson.getBoolean("Success")){
map.put("success", true);
}else{
map.put("success", false);
map.put("errMsg", dataJson.getString("Reason"));
}
} catch (Exception e) {
map.put("errMsg","快递接口调用出错。");
e.printStackTrace();
}
return map;
}
/** - Json way inquiry Order Logistics trajectory
- @throws Exception
*/
public static 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;
}
/** - Json way Logistics Subscription
- @throws Exception
*/
public static String orderTracesSubByJson(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", "1008");
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;
}
/** - Push data to determine whether to enter the courier from birds
- @param RequestData
- @param DataSign
- @return
*/
public static boolean isFromKdniao(String RequestData,String DataSign){
try {
return encrypt(RequestData, AppKey, "UTF-8").equals(DataSign);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/** - MD5 encryption
- @param str content
- @param charset encoding
- @throws Exception br/>*/
@SuppressWarnings("unused")
private static 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
*/
private static String base64(String str, String charset) throws UnsupportedEncodingException{
String encoded = base64Encode(str.getBytes(charset));
return encoded;
} br/>@SuppressWarnings("unused")
private static String urlEncoder(String str, String charset) throws UnsupportedEncodingException{
String result = URLEncoder.encode(str, charset);
return result;
}
/** - Sign signature generation electricity supplier
- @param content content
- @param keyValue Appkey
- @param charset encoding
- @throws UnsupportedEncodingException ,Exception
- @return DataSign签名br/>*/
@SuppressWarnings("unused")
private static 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);
}
/** - POST method request sent to the designated URL
- URL @param url send request
- @Param params request parameter set
- response result @return remote resource br /> * /
@SuppressWarnings ( "unused")
Private sendPost static String (String URL, the Map <String, String> the params) {
the OutputStreamWriter OUT = null;
the BufferedReader in = null;
the StringBuilder new new Result = the StringBuilder ();
the try {
the URL = new new realUrl the URL (URL);
the HttpURLConnection Conn = (the HttpURLConnection) realUrl.openConnection ();
// send a POST request must set the following two lines
conn.setDoOutput (to true);
conn.setDoInput (to true) ;
// the POST method
conn.setRequestMethod ( "the POST");
// common setting request attribute
conn.setRequestProperty ( "Accept", " / ");
conn.setRequestProperty ( "Connection", "the 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 ());
}
// the flush buffered output stream
out.flush ();
// read the input stream defined BufferedReader URL response
in = new new BufferedReader (
new new the InputStreamReader (conn.getInputStream () , "UTF-. 8"));
String Line;
the while ((Line = in.readLine ()) = null) {!
result.append (Line);
}
} the catch (Exception E) {
e.printStackTrace ();
}
// use finally block to close the output stream, the input stream
finally {
the try {
IF (OUT = null!) {
the out.close ();
}
IF (= null in!) {
in.close ();
}
}
the 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', '+', '/' };
private 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();
}
}