WebClient 的POST、GET

WebClient、POST、GET

WebClient

https://docs.microsoft.com/zh-TW/dotnet/api/system.net.webclient?view=netframework-4.7.2

保哥的注意事項參考

https://blog.miniasp.com/post/2010/01/23/Emulate-Form-POST-with-WebClient-class.aspx

 

GET

WebClient wc = new WebClient();

// 加上header,非必要,有些網站會吃header
// https://zh.wikipedia.org/wiki/HTTP%E5%A4%B4%E5%AD%97%E6%AE%B5
            
wc.Headers.Clear();
wc.Headers.Add("Accept", "text/html, application/xhtml+xml, */*");
wc.Headers.Add("Referer", "https://www.google.com");
wc.Headers.Add("Accept-Language", "zh-Hans-CN,zh-Hans;q=0.8,zh-Hant-TW;q=0.5,zh-Hant;q=0.3");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("Accept-Encoding", "gzip, deflate");
wc.Headers.Add("Cache-Control", "no-cache");

var page = wc.DownloadString("https://www.google.com");

 

POST

WebClient wc = new WebClient();

// 加上header,非必要,有些網站會吃header
// https://zh.wikipedia.org/wiki/HTTP%E5%A4%B4%E5%AD%97%E6%AE%B5
            
wc.Headers.Clear();
wc.Headers.Add("Accept", "text/html, application/xhtml+xml, */*");
wc.Headers.Add("Referer", "https://www.google.com");
wc.Headers.Add("Accept-Language", "zh-Hans-CN,zh-Hans;q=0.8,zh-Hant-TW;q=0.5,zh-Hant;q=0.3");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("Accept-Encoding", "gzip, deflate");
wc.Headers.Add("Cache-Control", "no-cache");

var postString ="search?q=.";
var postData = Encoding.UTF8.GetBytes(postString);
var page = wc.UploadData("https://www.google.com", postData);

 

範例僅供參考,網址參數需自行帶入

帶入的header或post data可用Fiddler擷取

https://www.telerik.com/fiddler