.Net(c#)模擬Http請求之HttpWebRequest封裝

1、需求:

  向某個服務發起請求獲取數據,如:爬蟲,採集。ide

2、步驟(HttpWebRequest):

無非在客戶端Client(即程序)設置請求報文(如:Method,Content-Type,Agent,Cookie以及請求參數等信息)向服務端Server發送請求,服務端響應數據。post

3、源碼簡介:

①.HttpUtil類:HttpWebRequest封裝的核心測試

②.HttpRequestParameter類:請求報文類url

③.HttpResponseParameter類:響應報文類spa

④.HttpCookieType類:請求/響應須要的Cookie封裝3d

4、運行測試:

class Program
{
    static void Main(string[] args)
    {
        IHttpProvider httpProvider = new HttpProvider();

        // 1. 模擬一個Get請求方式
        HttpResponseParameter responseParameter1 = httpProvider.Excute(new HttpRequestParameter
        {
            Url = "http://www.baidu.com",
            IsPost = false,
            Encoding = Encoding.UTF8
            //Cookie = new HttpCookieType() 若是須要Cookie
        });
        System.Console.WriteLine(responseParameter1.Body);

        // 2. 模擬一個Post請求方式(例:登陸)
        IDictionary<string, string> postData = new Dictionary<string, string>();
        postData.Add("userName", "登陸用戶名");
        postData.Add("userPwd", "用戶名密碼");
        HttpResponseParameter responseParameter2 = httpProvider.Excute(new HttpRequestParameter
        {
            Url = "你的登陸url",
            IsPost = true,
            Encoding = Encoding.UTF8,
            Parameters = postData
        });
        System.Console.WriteLine(responseParameter2.Body);

        System.Console.ReadLine();
    }
}

盡情地隨心所欲吧……code

5、源碼下載:點我

相關文章
相關標籤/搜索