基于多线程编写HttpWebRequest访问网页同步等待

有很多时候获取网页POST /GET的时候直接使用HttpWebRequest会影响主线程序的运行,视觉上有卡卡的感觉,这个时候又不想用异步,又想用多线程情的况下,能等待获取到信息后再执行下面的代码过程,因此封装了一个HttpHelper库,方便使直接调用就行了,支持代理 cookies 超时值自定义协议头,后期准备封装多线程下载之类的。

public class Response
    {
        /// <summary>
        /// 完整网址
        /// </summary>
        public string StrUrl { get; set; }
        /// <summary>
        /// 访问方式
        /// </summary>
        public string Method { get; set; } = "GET";
        /// <summary>
        //提交信息
        /// </summary>
        public string StrSubmitInfo { get; set; }
        /// <summary>
        /// 代理地址
        /// </summary>
        public string ProxyIp { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        public string strUserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string StrPassword { get; set; }
Response SubmitInfo = ParObject as Response;
            HttpWebRequest request = null;
            if (SubmitInfo.StrUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                request = WebRequest.Create(SubmitInfo.StrUrl) as HttpWebRequest;
            }
            else
            {
                request = WebRequest.Create(SubmitInfo.StrUrl) as HttpWebRequest;
            }
            if (!string.IsNullOrEmpty(SubmitInfo.ProxyIp))
            {
                WebProxy proxyObject = new WebProxy(SubmitInfo.ProxyIp, true);//为IP地址 port为端口号 代理类
                if (!string.IsNullOrEmpty(SubmitInfo.strUserName) && string.IsNullOrEmpty(SubmitInfo.StrPassword))
                    request.Proxy.Credentials = new NetworkCredential(SubmitInfo.strUserName, string.Empty);
                else if (!string.IsNullOrEmpty(SubmitInfo.strUserName) && !string.IsNullOrEmpty(SubmitInfo.StrPassword))
                    request.Proxy.Credentials = new NetworkCredential(SubmitInfo.strUserName, SubmitInfo.StrPassword);
                request.Proxy = proxyObject;
            }
            if (string.IsNullOrEmpty(SubmitInfo.UserAgent))
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
            if (SubmitInfo.cookies != null)
            {

使用方式

使用方式 
HttpHelper http = new HttpHelper();
http.CreateGetHttpResponse(new Response(){StrUrl = "http://www.baidu.com/"});//GET方式
http.CreateGetHttpResponse(new Response()
{StrUrl = "http://www.baidu.com/",
Method = "POST",parameters = "123",
header = new Dictionary<string, string>()
{
{"Accept-Language","cs,en-us;q=0.7,en;q=0.3"},
{"Accept-Encoding", "gzip, deflate"}
}
});/POST方式

下载地址https://download.csdn.net/download/showSoft/12412963

猜你喜欢

转载自blog.csdn.net/showSoft/article/details/106084018
今日推荐