咱們如今先在瀏覽器訪問一下,看到下面返回的結果:json
接下來就是你們最喜歡的寫代碼環節,爲了方便演示,咱們這裏用winform程序。很是簡單,咱們新建一個窗體程序,點擊後,彈出JSON數據便可。界面以下:瀏覽器
建好窗體,放一個按鈕,而後咱們來建立一個類HttpUitls。這個是這個文章中最重要的。app
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namespace WindowsFormsApplication1 { public class HttpUitls { public static string Get(string Url) { //System.GC.Collect(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Proxy = null; request.KeepAlive = false; request.Method = "GET"; request.ContentType = "application/json; charset=UTF-8"; request.AutomaticDecompression = DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if (response != null) { response.Close(); } if (request != null) { request.Abort(); } return retString; } public static string Post(string Url, string Data, string Referer) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.Referer = Referer; byte[] bytes = Encoding.UTF8.GetBytes(Data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; Stream myResponseStream = request.GetRequestStream(); myResponseStream.Write(bytes, 0, bytes.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if (response != null) { response.Close(); } if (request != null) { request.Abort(); } return retString; } } }
這個類有兩個方法,一個是Get,一個是Post,本篇文章咱們只須要用到Get就能夠了。post
而後是點擊按鈕的方法url
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //咱們的接口 string url = "http://www.kuaidi100.com/query?type=shunfeng&postid=367847964498"; //將接口傳入,這個HttpUitls的類,有興趣能夠研究下,也能夠直接用就能夠,不用管如何實現。 string getJson = HttpUitls.Get(url); MessageBox.Show(getJson); } } }
而後是運行結果spa
到這一步說明咱們已經成功拿到接口給咱們返回的JSON數據了。那麼咱們會在下一篇文章中講解如何使用這JSON數據,也就是解析JSON3d