8月份換了份工作,是做物流行業相關系統的,有時會需要查詢外部快遞接口,進行快遞跟蹤查詢,這里就抓取快遞100數據進行簡單介紹。
需要的朋友可以參考下。
先上效果圖:
下面我們一步一步來討論如何實現這樣的功能。
1、准備工作:獲取快遞100 Json數據
由上圖我們發現 快遞100的查詢路勁為:http://www.kuaidi100.com/query?type=yuantong&postid=5714113854&id=1&valicode=&temp=0.19689508604579842
重要的兩個參數是type:快遞公司代碼, postid:快遞單號
2、設計代碼--設計類
這里有一個小技巧,我們復制 json 數據。
1 public class ExpressStack<T> 2 { 3 public string message { get; set; } 4 public string nu { get; set; } 5 public string ischeck { get; set; } 6 public string com { get; set; } 7 public string status { get; set; } 8 public string condition { get; set; } 9 public string state { get; set; } 10 public List<T> data { get; set; } 11 } 12 13 public class Data 14 { 15 public string time { get; set; } 16 public string context { get; set; } 17 public string ftime { get; set; } 18 }
這樣我們不用寫代碼,類就設計好了(有刪改),我們使用了泛型類來處理Json數據。
3、編寫Action
這個就比較簡單,一些json轉換和輸出
public ActionResult Search() { return View(); } [HttpPost] public ActionResult Search(string type, string postId) { WebClient wClient = new WebClient(); wClient.Encoding = Encoding.UTF8; var response = wClient.DownloadString("http://www.kuaidi100.com/query?type=" + type + "&postid=" + postId); var oJson = JsonConvert.DeserializeObject<ExpressStack<Data>>(response); return View(oJson); }
4、View 顯示數據
這里不做異常處理,大家可以自己加上
@using KuaiDi100.Controllers; @model ExpressStack<Data> <h2>快遞查詢</h2> @using (Html.BeginForm("Search", "KuaiDi100", FormMethod.Post, new { @class = "form-inline margin-bottom-10 ", style = "margin-left:200px" })) { <div class="form-group"> <div class="col-md-10"> <label class="control-label">快遞公司代碼</label> <input type="text" name="type" class="form-control" /> </div> </div> <div class="form-group"> <label class="control-label">快遞單號</label> <input type="text" name="postId" class="form-control" /> </div> <div class="form-group"> <div class="col-md-10"> <button class="btn btn-primary">查詢</button> </div> </div> } <table class="table table-striped table-bordered table-hover table-full-width" style="overflow:scroll; margin-top:50px;"> <thead> <tr> <th>地點和跟蹤進度</th> <th>時間</th> </tr> </thead> <tbody> @if (Model != null) { if (Model != null) { foreach (var item in Model.data) { <tr> <td>@item.context</td> <td>@item.time</td> </tr> } } else { <tr> <td style="text-align:center" colspan="2">暫無結果</td> </tr> } } else { <tr> <td style="text-align:center" colspan="2">暫無結果</td> </tr> } </tbody> </table>
運行效果就和上面第一張圖一樣了,源碼都在上面了,需要的朋友可以參考下, 如果有幫助到你,請點擊好文要頂按鈕,謝謝支持.