C# 實現對網站Get與Post請求

通過配合new WebClient()自己封裝接口HttpGetPage(string url,string coding)用戶傳入網站地址以及編碼方式,即可下載指定頁面到變量中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static string HttpGetPage(string url,string coding)
        {
            string pageHtml = string.Empty;
            try
            {
                using(WebClient MyWebClient = new WebClient())
                {
                    Encoding encode = Encoding.GetEncoding(coding);
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;
                    Byte[] pageData = MyWebClient.DownloadData(url);
                    pageHtml = encode.GetString(pageData);
                }
            }
            catch { }
            return pageHtml;
        }

        static void Main(string[] args)
        {
            var html = HttpGetPage("https://www.baidu.com","utf-8");

            Console.WriteLine(html);
            Console.ReadKey();
        }
    }
}

POST請求與Get類似,此處封裝一個HttpPost(url, dic);函數,傳入網站路徑以及需要推送的鍵值對,即可使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        public static string HttpPost(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36";
            req.ContentType = "application/x-www-form-urlencoded";
            #region
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //獲取響應內容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        static void Main(string[] args)
        {
            string url = "http://www.baidu.com/";
            Dictionary<string, string> dic = new Dictionary<string, string> { };
            dic.Add("username","lyshark");
            HttpPost(url, dic);

            Console.ReadKey();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章