小組件---快遞查詢組件


        最近翻一翻郵件,發現有以前實習的時候幫公司做的一個獲取快遞網站的快遞信息.Net組件,我copy出來了的。現在就分享一下。

       一.調研快遞100網

           1. 通過httpwatch抓取了快遞100網查詢快遞的地址 http://m.kuaidi100.com/query,API訪問格式是  queryUrl + "?type=" +快遞公司類型+ "&postid=" + 快遞單號;

               我的另一篇博客里面有寫到如何抓取:  一個有用的網絡監控軟件

           2. 默認返回Json字符串格式是:

{"message":"ok","status":"1","state":"3","data":
            [{"time":"2012-07-07 13:35:14","context":"客戶已簽收"},
             {"time":"2012-07-07 09:10:10","context":"離開 [北京石景山營業廳] 派送中,遞送員[溫],電話[]"},
             {"time":"2012-07-06 19:46:38","context":"到達 [北京石景山營業廳]"},
             {"time":"2012-07-06 15:22:32","context":"離開 [北京石景山營業廳] 派送中,遞送員[溫],電話[]"},
             {"time":"2012-07-06 15:05:00","context":"到達 [北京石景山營業廳]"},
             {"time":"2012-07-06 13:37:52","context":"離開 [北京_同城中轉站] 發往 [北京石景山營業廳]"},
             {"time":"2012-07-06 12:54:41","context":"到達 [北京_同城中轉站]"},
             {"time":"2012-07-06 11:11:03","context":"離開 [北京運轉中心駐站班組] 發往 [北京_同城中轉站]"},
             {"time":"2012-07-06 10:43:21","context":"到達 [北京運轉中心駐站班組]"},
             {"time":"2012-07-05 21:18:53","context":"離開 [福建_廈門支公司] 發往 [北京運轉中心_航空]"},
             {"time":"2012-07-05 20:07:27","context":"已取件,到達 [福建_廈門支公司]"}
            ]} 

         二. 定義實體類.
             按照Json格式定義,實體類:

             Notes:1.MQueryParameter 查詢條件 ;2.MResultMsg 查詢后的返回結果; 3.ExpressageInfo單個時間段的物流情況;4.ErrorMsg:記錄存儲訪問錯誤,包括配置文件錯誤,以及web訪問錯誤

    public class MQueryParameter
    {
        /// <summary>
        /// 快遞公司
        /// </summary>
        public string TypeCom { get; set; }

        /// <summary>
        /// 快遞訂單號
        /// </summary>
        public string OrderId { get; set; }
    }

    public class MResultMsg
    {
        public bool Result { get; set; }

        public StateType State { get; set; }

        public string JsonMessage { get; set; }

        public List<ExpressageInfo> Data { get; set; }

        public ErrorMsg Error { get; set; }
    }

    public class ExpressageInfo
    {
        
        public DateTime Time { get; set; }

        public string Context { get; set; }
    }

    public enum StateType
    {
        在途,
        攬件,
        疑難,
        簽收,
        退簽,
        派件,
        退回
    }

    public class ErrorMsg
    {
        public string ErrorCode { get; set; }

        public string ErrorMessage { get; set; }
    }

        三.配置文件.
             對於查詢的API URI 我們應該用配置文件存儲起來,以及快遞的Map信息. 主要是用於放置API變化.

        Note: xml里面用到了轉義:&(邏輯與)  &amp; <(小於) &lt; >(大於) &gt; "(雙引號)  &quot; '(單引號)  &apos; [/size]

<configuration>
  <appSettings>    
    <!--手機api服務器訪問地址-->
    <add key="queryUrl" value="http://m.kuaidi100.com/query?type={0}&amp;postid={1}" />
    <!--順豐快遞對應的編碼-->
    <add key="順豐速遞" value="shunfeng"/>
    <add key="中通速遞" value="zhongtong"/>
  </appSettings>
</configuration>

         三.Helper方法.
             通過Helper的提供的方法對QueryParam參數的Check以及數據獲取,方法里面的所有異常都必須處理。組件按理是不能出現讓程序崩潰的情況的。所以所有異常必須處理。然后封裝到ErrorMsg對象中.

 public static MResultMsg GetExpressageMessage(MQueryParameter para)
        {
            // 獲取配置文件
            Configuration config = null;
            string queryUrl = string.Empty;
            string com = string.Empty;
            MResultMsg msg = new MResultMsg();if (string.IsNullOrEmpty(para.TypeCom))
            {
                msg.Result = false;
                msg.Error = new ErrorMsg() { ErrorCode = "001", ErrorMessage = "物流公司不能為空" };
                return msg;
            }

            if (string.IsNullOrEmpty(para.OrderId))
            {
                msg.Result = false;
                msg.Error = new ErrorMsg() { ErrorCode = "002", ErrorMessage = "訂單號不能為空" };
                return msg;
            }

            try
            {
                string configPath = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Expressage.config");
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = configPath;
                config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                queryUrl = config.AppSettings.Settings["queryUrl"] == null ? string.Empty : config.AppSettings.Settings["queryUrl"].Value;                
                com = config.AppSettings.Settings[para.TypeCom] == null ? string.Empty : config.AppSettings.Settings[para.TypeCom].Value;
            }
            catch (Exception ex)
            {
                msg.Result = false;
                msg.Error = new ErrorMsg() { ErrorCode = "003", ErrorMessage = ex.Message };
                return msg;
            }
           
            if (string.IsNullOrEmpty(com))
            {
                msg.Result = false;
                msg.Error = new ErrorMsg() { ErrorCode = "004", ErrorMessage = "配置文件缺少對於的物流公司類型" };                
                return msg;
            }

            // 網上獲取物流信息    
            string jsonResult = null;
            try
            {
                queryUrl = string.Format(queryUrl, com, para.OrderId);
                WebRequest request = WebRequest.Create(@queryUrl);
                WebResponse response = request.GetResponse();
                string message = string.Empty;
                using (Stream stream = response.GetResponseStream())
                {
                    Encoding encode = Encoding.UTF8;
                    using (StreamReader reader = new StreamReader(stream, encode))
                    {
                        message = reader.ReadToEnd();
                    }
                    jsonResult = message;
                }
            }
            catch (Exception ex)
            {
                msg.Result = false;
                msg.Error = new ErrorMsg() { ErrorCode = "005", ErrorMessage = ex.Message };
                return msg;
            }

            msg = JSONStringToObj<MResultMsg>(jsonResult);
            msg.JsonMessage = jsonResult;
            msg.Result = true;
            return msg;
        }

        private static T JSONStringToObj<T>(string JsonStr)
        {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            T objs = Serializer.Deserialize<T>(JsonStr);
            return objs;
        }

           四. 下載地址:
              Frank.Expressage.zip 里面有一個測試數據,可能時間過太久里面那個快遞單號也會出現過期情況查詢不到數據.

           五.總結

               代碼是以前寫的沒做修改,就貼上來了。感覺有點不厚道,因為那個Uri是自己用httpwatch抓的。單獨獲取API 希望大家還是訪問官網去申請吧。抓取的uriApi對用戶有訪問頻率限制的。訪問過於頻繁。就會被封掉。 下面是官網地址,請支持正版:  http://www.kuaidi100.com/openapi/applyapi.shtml

 

 

     

            

 

     

    

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM