How Java writes logistics interface, how to access logistics interface, how to query logistics tracking details according to single number
- demand
According to the order number inputted by users, our backstage identifies the order number and inquires the Api interface of express delivery according to the express bird to realize the function of automatic inquiry.
- demo example
Demo I've run myself - > click on me to download
- Application scenarios (below)
- Implementation steps
4.1 This interface uses Express Bird Logistics Interface Express Bird API Interface - to provide the most comprehensive logistics API services for the business.
Application for Express Bird API Interface Web Site: Express Bill Inquiry Interface Electronic Form APIKey Authorization Application Express Bird Account Registration
4.2 Click to enter the Express Bird Registration Account, then login to the Application Interface (the application will only provide you the merchant ID and API key)
4.3 After successful login, according to the prompt information, complete the information in turn, Click to submit the application. You can see the business ID and API key and other information, with which you can request queries and other interface Api.
4.4 This is the acquired business ID and API key values (which will be used in Demo later)
- Demo is written by a third party and can be run by downloading only. (Make simple modifications by yourself)
Below is the website for downloading Demo. According to your needs, you can download the api interface document for express logistics and download the electronic single interface document - the Bird code interface document for express delivery.
- The following is the detailed code for querying logistics tracking information based on document number in java version
6.1 Create KdniaoTrackQuery API interface class
package com.ssm.jock.utils;
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
- @ see: Express Bird API Interface - Providing the most comprehensive logistics API services for vendors
- @ Copright: Shenzhen Quick Gold Data Technology Service Co., Ltd.
* - E-commerce ID and private key in DEMO are only used for testing. For formal environment, please register your account separately.
- More than 500 single queries per day. It is suggested to connect to our logistic trajectory subscription push interface.
- ID and Key please go to the official website to apply: Express Bill Inquiry Interface Electronic Form APIKey Authorization Application Express Bird Account Registration
*/
public class KdniaoTrackQueryAPI {
//E-commerce ID (Business ID of Fast Bird Application) private String EBusinessID="*******"; //E-commerce encryption private key, courier bird provides, take care of the storage, do not leak (fast bird application API key value) private String AppKey="*************************"; //Request url private String ReqURL="http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx"; /** * Json Way to Query Order Logistics Trajectory * @throws Exception * ShipperCode Abbreviation of Delivery Express * LogisticCode Courier number */ 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); //Processing the returned information according to the company's business... return result; } /** * MD5 encryption * @param str content * @param charset Coding mode * @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 Code * @param str content * @param charset Coding mode * @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 Signature Generation in E-commerce * @param content content * @param keyValue Appkey * @param charset Coding mode * @throws UnsupportedEncodingException ,Exception * @return DataSign autograph */ @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); } /** * Send a request for a POST method to a specified URL * @param url The URL to send the request * @param params Request parameter set * @return RESPONSE RESULTS OF REMOTE RESOURCES */ @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(); // To send a POST request, you must set the following two lines conn.setDoOutput(true); conn.setDoInput(true); // POST method conn.setRequestMethod("POST"); // Setting Common Request Properties 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(); // Get the output stream corresponding to the URLConnection object out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // Send request parameters 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()); } // Buffer of flush output stream out.flush(); // Define the BufferedReader input stream to read the response of the 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(); } //Close the output and input streams using the final block 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(); }
}
6.2 Below is Demo's main method test code
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
// Test interface
public class Demo {
public static void main(String[] args) { KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI(); try { //The first parameter is the express company abbreviation (YD - Yunda Express) //The second parameter is the courier number that needs to be queried. String result = api.getOrderTracesByJson("YD", "3827670147715"); JSONObject jsonObject = JSONObject.fromObject(result); String ShipperCode = jsonObject.getString("ShipperCode"); String LogisticCode = jsonObject.getString("LogisticCode"); JSONArray Traces = jsonObject.getJSONArray("Traces"); System.out.print(result+"\n"); System.out.println("Express name"+ShipperCode); System.out.println("Courier number"+LogisticCode); for(int i = 0; i < Traces.size(); i++) { JSONObject object = (JSONObject) Traces.get(i); String AcceptTime = object.getString("AcceptTime"); String AcceptStation = object.getString("AcceptStation"); System.out.println("Time:"+AcceptTime+"\t"+AcceptStation); } } catch (Exception e) { e.printStackTrace(); } }
}
6.3 Screenshots of test results
- Tips
The demo downloaded does not convert json format into String format output, so it needs to be written by itself. To change to json format, you need to download several jar packages.
commons-beanutils-1.8.3.jar
commons-collections-3.2.jar
commons-httpclient-1.0.jar
commons-lang-2.4.jar
commons-logging-1.2.jar
ezmorph-1.0.jar
json-lib-2.4-jdk15.jar
morphia-1.0.jar
To download the jar package, you can go to Aliyun to download the warehouse service (download site below).