Express Bird Logistics Single Number Query api interface integration, can be directly used if necessary

Keywords: Programming Java xml Apache JSON

With the development of online shopping, the express industry has also grown. The demand for the docking of express inquiry interface is also growing. The following is the collation of free express interface, with the call process attached, to share with you.

In the project development, some requirements will inevitably use some Api interfaces about express delivery; this article mainly introduces the Api interface of express bird query.

Achievable requirements:

  1. Implementation of Api Interface for Express Logistics Information Query by Direct Integration in App
  2. In the public address, micro mall, e-commerce website platform, according to the user's input order number, our background recognition order number and according to the express bird query the express Api interface, realize the function of automatic inquiry.

Official website:  http://www.kdniao.com

Instant query api: http://www.kdniao.com/api-track

Need to log in, apply for user ID and API key

Application scenarios

1. Buyer's logistics inquiries: trajectory tracking, package progress, expected service time, dispatched person's contact mode and so on.

(2) Seller Logistics Tracking: Are there any oversize areas, transfers, multiple deliveries and rejections?

(3) Platform monitoring and management: false transaction monitoring, matching the seller's delivery time and customer's confirmation of receipt time.

Multi-language demo can be implemented, taking javademo as an example:

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 {
    
    //Electricity supplier ID
    private String EBusinessID="1237100";    
    //E-commerce encryption private key, courier bird provided, take care to keep, do not leak (need to re-apply ID)
    private String AppKey="518a73d8-1f7f-441a-b644-33e77b49d846";    
    //Request url
    private String ReqURL="http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";    
 
    /**
     * Json Mode Logistics Information Subscription
     * @throws Exception 
     */
    public String orderTracesSubByJson() throws Exception{
        String requestData="{'Code': 'SF','Item': ["+
                           "{'No': '909261024507','Bk': 'test'},"+
                           "{'No': '589554393102','Bk': 'test'},"+
                           "{'No': '589522101958','Bk': 'test'},"+
                           "{'No': '909198822942', 'Bk': 'test'}"+
                           "]}";
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", "1005");
        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;
    }
    
    /**
     * XML Mode Logistics Information Subscription
     * @throws Exception 
     */
    public String orderTracesSubByXml() throws Exception{
        String requestData="<?xml version=\"1.0\" encoding=\"utf-8\" ?>"+
                            "<Content>"+
                            "<Code>SF</Code>"+
                            "<Items>"+
                            "<Item>"+
                            "<No>909261024507</No>"+
                            "<Bk>test</Bk>"+
                            "</Item>"+
                            "<Item>"+
                            "<No>909261024507</No>"+
                            "<Bk>test</Bk>"+
                            "</Item>"+
                            "</Items>"+
                            "</Content>";
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", "1005");
        String dataSign=encrypt(requestData, AppKey, "UTF-8");
        params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "1");
        
        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 = 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 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();
    }
}

Posted by Boris Senker on Thu, 03 Oct 2019 20:59:20 -0700