WinForm程序访问OpenAP查询快递

上次在看到博客园上有一篇通过winform访问查询快递的OpenAPI文章,没有交待怎么实现,也没有代码,所以自己试了下,通过两种方法成功查询到快递信息。

1,通过 HttpWebRequest和HttpWebResponse

       HttpWebRequest request = HttpWebRequest.Create("http://api.kuaidi100.com/apione" + "?com="+comboBox2.SelectedText+"&nu="+comboBox1.SelectedText+"&show=4") as HttpWebRequest;
request.Method = "GET";
request.ContentType = "text/plain";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream,System.Text.Encoding.Default);
string result = reader.ReadToEnd();
tbresult.Text = result;
stream.Close();
 
  

2,通过WebClient

WebClient client = new WebClient();
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.Encoding = System.Text.Encoding.UTF8;
tbresult.Text=client.DownloadString("http://api.kuaidi100.com/apione" + "?com=" + comboBox2.Text + "&nu=" + comboBox1.Text + "&show=3");

用WebClinet相对HttpWebRequest和HttpWebResponse来说更简单一些,另外还可以进行异步传输,所以我比较喜欢用WebClient

当然,还可以使用WebBrowser,不过WebBrowser主要用来浏览,这里只是获取数据,就没必要了

你可能感兴趣的:(WinForm)