基于HttpWebRequest和HttpWebResponse的HttpHelper
C#中实现POST的方法很多,常用的是WebBrowser、WebClient、HttpWebRequest和HttpWebResponse。
1、WebBrowser基本是在DocumentCompleted中分析HtmlDocument ;
2、WebClient是对HttpWebRequest和HttpWebResponse的封装,用起来更方便,但是灵活性还是不及HttpWebRequest和HttpWebResponse;
3、HttpWebRequest和HttpWebResponse更底层,灵活度更好,不过代码更多,我做了一个简单的封装,将GET改成分段读取,并加入代理、进度条和错误重试处理。代码如下:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Van.Base
{
public class HttpHelper
{
#region 委托 事件
public delegate void dgtProgValueChanged(long Value);
/// <summary>
/// 进度改变事件
/// </summary>
public event dgtProgValueChanged OnProgValueChanged;
#endregion
#region 属性
/// <summary>
/// 代理
/// </summary>
public WebProxy Proxy { get; set; }
/// <summary>
/// Cookie
/// </summary>
public CookieContainer UserCookie { get; set; }
/// <summary>
/// 重试次数
/// </summary>
public int IAfreshTime { get; set; }
/// <summary>
/// 错误次数
/// </summary>
public int IErrorTime { get; private set; }
long m_ProgValue = 0;
/// <summary>
/// 当前读取字节
/// </summary>
public long ProgValue
{
get { return m_ProgValue; }
private set
{
m_ProgValue = value;
if (OnProgValueChanged != null)
{
OnProgValueChanged(value);
}
}
}
/// <summary>
/// 待读取最大字节
/// </summary>
public long ProgMaximum { get; private set; }
#endregion
#region 方法
#region Get
/// <summary>
/// 获取HTML
/// </summary>
/// <param name="URL">地址</param>
/// <param name="Accept">Accept请求头</param>
/// <returns>Html代码</returns>
public string GetHTML(string URL, string Accept)
{
return GetHTML(URL, Accept, System.Text.Encoding.UTF8);
}
/// <summary>
/// 获取HTML
/// </summary>
/// <param name="URL">地址</param>
/// <param name="Accept">Accept请求头</param>
/// <param name="encoding">字符编码</param>
/// <returns>Html代码</returns>
public string GetHTML(string URL, string Accept, Encoding encoding)
{
return GetHTML(URL, Accept, encoding, 1024);
}
/// <summary>
/// 获取HTML
/// </summary>
/// <param name="URL">地址</param>
/// <param name="Accept">Accept请求头</param>
/// <param name="encoding">字符编码</param>
/// <param name="bufflen">数据包大小</param>
/// <returns>Html代码</returns>
public string GetHTML(string URL, string Accept, Encoding encoding, int bufflen)
{
IErrorTime = 0;
return _GetHTML(URL, Accept, encoding, bufflen);
}
/// <summary>
/// 获取HTML
/// </summary>
 
补充:软件开发 , C# ,