通过配合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();
}
}
}