Java How to Dock Express Bird Logistics Single Query api Interface Specific Steps

Keywords: Front-end Java JSON encoding Windows

Main functions: According to the order number entered by the user, automatically recognizes the API interface of Express Bird Query to achieve the function of automatic query.

First look at the picture:

Here is a complete docking process

Step 1: http://www.kdniao.com/reg  Enter this website to register for your own account

Once you have registered, go into improving your personal information, which is the user Id and API key provided by your website, which you will need to write code for.

Then you enter the product service management, you can see various services, the top of which is the free one-year logistics inquiry service, choose to order now,

Then you will be allowed to authenticate. If you are an enterprise, you can fill in the enterprise information normally, if you do not select individual users.

Okay, you're done with the official website.The first step is to access the official website for relevant information.

Step 2: In http://www.kdniao.com/HelpDoc/FAQ/DocDes.aspx This website downloads demo, and I'm writing a query, so I just set up a demo for Instant Query.

Once the download is complete, I can start working. I created a new tool class in the project's tool class.

Yes, demo is as follows:

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
 *
 * @Technical QQ Group: 456320272
 * @see: http://www.kdniao.com/YundanChaxunAPI.aspx
 * @copyright: Shenzhen Quick Gold Data Technology Service Co., Ltd.
 *
 * DEMO E-commerce ID s and private keys are for testing purposes only. Please register your account separately in the formal environment
 * More than 500 inquiries per day, recommended access to our logistics track subscription push interface
 * 
 * ID And Key, please go to the official website to apply: http://www.kdniao.com/ServiceApply.aspx
 */

public class KdniaoTrackQueryAPI {
    //E-commerce ID
    private String EBusinessID="Please apply to the Express Bird website http://www.kdniao.com/ServiceApply.aspx";
    //E-commerce encryption private key, courier bird provided, take care to keep, do not leak
    private String AppKey="Please apply to the Express Bird website http://www.kdniao.com/ServiceApply.aspx";
    //Request url
    private String ReqURL="http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";    
 
    /**
     * Json Method Query Order Logistics Track
     * @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 information based on company business processes...
        
        return result;
    }
 
    /**
     * MD5 encryption
     * @param str Content)
     * @param charset Encoding Method
     * @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 Encoding Method
     * @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;
    }
    
    /**
     * E-commerce Sign ature Generation
     * @param content Content
     * @param keyValue Appkey  
     * @param charset Encoding Method
     * @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 POST method request to specified URL
     * @param url URL to send the request
     * @param params Requested parameter set
     * @return Response results from 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();
            // Sending a POST request must be set to 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();
            // Gets 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());
            }
            // Buffering 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();
        }
        //Use finally blocks to close output and input streams
        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(); 
    }
}
 

This is a specific tool class, because I am based on the SSM framework, so the next step is the server layer.

Then there's serviceImpl

package com.hs.service.impl;

import com.hs.service.ExpressageService;
import com.hs.utils.KdniaoTrackQueryAPI;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: todo
 * Author: lanxiaowei
 * Date: Created in 2018/8/28 10:52
 */
@Service
public class ExpressageServiceImpl extends  BaseServiceImpl implements ExpressageService{

    /**
     * Tracking information based on courier number
     * @param cohr
     * @param ExpressNumber
     * @return
     */
    @Override
    public Map<String, Object> findExpressageInfo(String cohr, String ExpressNumber) {
        Map<String,Object> map = new HashMap<>();
        KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
        try {
            //The first parameter is the courier company abbreviation (YD--YNDA Express)
            //The second parameter is the courier number that needs to be queried
            String result = api.getOrderTracesByJson(cohr, ExpressNumber);
            JSONObject jsonObject = JSONObject.fromObject(result);
            if(jsonObject.containsKey("ShipperCode")){
                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);
                int count = 1;
                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);
                    map.put("time"+count,AcceptTime+AcceptStation);
                    count++;
                }}
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("End");
        }
        return map;
    }
    }

The last step is the control layer:

@Controller
@RequestMapping("expressage")
public class ExpressageController {

    @Autowired
    private ExpressageService expressageService;

    /**
     * Track courier information based on courier number
     * @param cohr
     * @param ExpressNumber
     * @return
     */
    @RequestMapping(value="findExpressageInfo.do" ,method= RequestMethod.POST,
            produces="application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> findExpressageInfo(@RequestParam("cohr") String cohr,
                                                 @RequestParam("ExpressNumber") String ExpressNumber){
        return expressageService.findExpressageInfo(cohr,ExpressNumber);
    }
}

Okay, that's it, because I'm an ancestor of mine, and said the downloaded demo didn't convert the jsong format to the String format output, so I need to write it myself, so I need a jar package.

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

Posted by grungefreak on Sun, 29 Sep 2019 22:50:49 -0700