WebClient Post 数据 ,支持Cookie

WebClient web = new CookieWebClient();
web.Encoding = Encoding.UTF8;
string regUrl = "http://test.com";
web.Headers.Add("Content-Type","POST", "application/x-www-form-urlencoded");
byte[] post = Encoding.UTF8.GetBytes("u=aa&p=bb");byte[] data = web.UploadData(regUrl, post);string html = Encoding.UTF8.GetString(data);

 
  
/// 
/// 带 Cookie 的 WebClient
/// 
public class CookieWebClient : WebClient
{
	// Cookie 容器
	public CookieContainer Cookies;

	/// 
	/// 创建一个新的 CookieWebClient 实例。
	/// 
	public CookieWebClient()
	{
		this.Cookies = new CookieContainer();
	}

	protected override WebRequest GetWebRequest(Uri address)
	{
		WebRequest request = base.GetWebRequest(address);
		if (request is HttpWebRequest)
		{
			HttpWebRequest httpRequest = request as HttpWebRequest;
			httpRequest.CookieContainer = Cookies;
		}
		return request;
	}
}


你可能感兴趣的:(.net代码片段)