创建一个类HttpUitls
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
获取json对象
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); } } }