8月份换了份工做,是作物流行业相关系统的,有时会须要查询外部快递接口,进行快递跟踪查询,这里就抓取快递100数据进行简单介绍。json
须要的朋友能够参考下。post
先上效果图:spa
下面咱们一步一步来讨论如何实现这样的功能。设计
由上图咱们发现 快递100的查询路劲为:http://www.kuaidi100.com/query?type=yuantong&postid=5714113854&id=1&valicode=&temp=0.196895086045798423d
重要的两个参数是type:快递公司代码, postid:快递单号code
这里有一个小技巧,咱们复制 json 数据。orm
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数据。blog
这个就比较简单,一些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); }
这里不作异常处理,你们能够本身加上ip
@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>
运行效果就和上面第一张图同样了,源码都在上面了,须要的朋友能够参考下, 若是有帮助到你,请点击好文要顶按钮,谢谢支持.