圓通面單下單接口

package com.mingwen.common.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 org.apache.commons.codec.binary.Base64;  
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.json.XML;

import lombok.extern.log4j.Log4j2;

@Log4j2
@SuppressWarnings("restriction")
public class YTOUtil {

    private static final String ReqURL = "http://customerewms.yto.net.cn/CommonOrderModeBPlusServlet.action";//正式地址
    private static final String partnerId = "xxxxxx";對應你自己的partnerId
    private static final String customerId = "xxxxx";k碼

    /**
     * 
     * @param tid  訂單號
     * @param itemName
     * @param number
     * @return
     * @throws Exception
     */
    public static String YTO(Map<String, Object> map) throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        String tid=map.get("tid").toString();//訂單號
        String receiverName=map.get("receiverName").toString();//收件人姓名
        String receiverPhone=map.get("receiverPhone").toString();//收件人電話
        String receiverProv=map.get("receiverProv").toString();//收件人地址省
        String receiverCity=map.get("receiverCity").toString();//收件人城市
        String receiverAddress=map.get("receiverAddress").toString();//收件人詳細地址
        
        
        String logistics_interface = "<RequestOrder>" 
                 +"    <clientID>" + customerId + "</clientID>" 
                 +"    <logisticProviderID>YTO</logisticProviderID>"
                 +"    <customerId>" + customerId + "</customerId>" 
                 +"    <txLogisticID>" + tid + "</txLogisticID>" 
                 +"    <orderType>1</orderType>" 
                 +"    <flag>1</flag>" 
                 +"    <type>0</type>" 
                 +"    <sender>" 
                 +"        <name>古的圖書技術有限公司</name>" 
                 +"        <postCode>231200</postCode>" 
                 +"        <phone>0551-68896884</phone>" 
                 +"        <mobile>18919654894</mobile>" 
                 +"        <prov>安徽省</prov>" 
                 +"        <city>合肥市</city>"
                 +"        <address>蜀山區決策大廈</address>" 
                 +"    </sender>"
                 +"    <receiver>" 
                 +"        <name>"+receiverName+"</name>" 
                 +"        <mobile>"+receiverPhone+"</mobile>" 
                 +"        <prov>"+receiverProv+"</prov>" 
                 +"        <city>"+receiverCity+"</city>"
                 +"        <address>"+receiverAddress+"</address>" 
                 +"    </receiver>"
                 +"    </RequestOrder>";

                 
        params.put("logistics_interface",URLEncoder.encode(logistics_interface, "UTF-8"));//消息內容
        params.put("data_digest", encrypt(logistics_interface, partnerId,"UTF-8"));//消息簽名
        params.put("clientId", customerId);//    客戶編碼(電商標識)
        params.put("type", "offline");//訂單類型(online:在線下單,offline:線下下單)

        String result=sendPost(ReqURL, params);
        return result;
    }

    /**
     * MD5加密
     */
    private static byte[] MD5(String str) throws Exception {
        MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(str.getBytes());
        return bytes;
    }

    /**
     * base64編碼
     */
    private static String base64(byte[] str) throws UnsupportedEncodingException {
          
        String encoded =Base64.encodeBase64String(str);
        return encoded;
    }

    /*
     * 編碼轉換
     */
    private static String urlEncoder(String str, String charset) throws UnsupportedEncodingException {
        String result = URLEncoder.encode(str, charset);
        return result;
    }

    /**
     * 簽名生成
     */
    private static String encrypt(String logistics_interface, String partnerId, String charset)
            throws UnsupportedEncodingException, Exception {
        if (partnerId != null) {
            return urlEncoder(base64(MD5(logistics_interface + partnerId)), charset);
        }
        return urlEncoder(base64(MD5(logistics_interface + partnerId)), charset);
    }
    


    /**
     * 發送POST請求
     */
    private static 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;charset=utf-8");
            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());
                    log.info(entry.getKey() + ":" + entry.getValue());
                }
                log.info("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();
    }
    
    

/**測試類**/


    public static void main(String[] args) throws Exception {
        String tid="419945282327986826";//訂單號
        String receiverName="吳順傑";//收件人姓名
        String receiverPhone="13721049111";//收件人電話
        String receiverProv="安徽省";//收件人地址省
        String receiverCity="合肥市";//收件人城市
        String receiverAddress="蜀山區新華學院";//收件人詳細地址
        Map<String, Object> map=new HashMap<>();
        map.put("tid", tid);
        map.put("receiverName", receiverName);
        map.put("receiverPhone", receiverPhone);
        map.put("receiverProv", receiverProv);
        map.put("receiverCity", receiverCity);
        map.put("receiverAddress", receiverAddress);
        String result=YTOUtil.YTO(map);
        JSONObject xmlJSONObj = XML.toJSONObject(result);  

        log.info(xmlJSONObj.toString());
    }


}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章