在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
方式一
string strResult = string.Empty;
//到这里为止 异步信息已经发出去了 如果不需要返回值 可以不需执行下面的步骤 //下面为返回服务器异步的信息
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse(); Response.Write(strResult);
//如果要追踪远端页面的错误,则可使用以下方式 HttpWebResponse HttpWResp; try } //则返回的信息中包含对方页面的错误提示
方法二
private WebRequest _request; AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation)); } public IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state) void EndAsyncOperation(IAsyncResult ar)
在各种不同的情况下选择异步的方式
-------------------------------------------------------------------------------------------------------------------------------------------------- 有时候会需要cookies验证...下面是保存cookies并模拟发送包含cookies的方法 CookieContainer cookies = new CookieContainer(); string url = "http://www.google.com.hk/";HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); myHttpWebRequest.Timeout = 20 * 1000; //连接超时 myHttpWebRequest.Accept = "*/*"; myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)"; myHttpWebRequest.CookieContainer = new CookieContainer(); //暂存到新实例 myHttpWebRequest.GetResponse().Close(); cookies = myHttpWebRequest.CookieContainer; //保存cookies string cookiesstr = myHttpWebRequest.CookieContainer.GetCookieHeader(myHttpWebRequest.RequestUri); //把cookies转换成字符串 url = "http://www.google.com.hk/search?oe=utf8&ie=utf8&source=uds&hl=zh-CN&q=3g"; myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); myHttpWebRequest.Timeout = 20 * 1000; //连接超时 myHttpWebRequest.Accept = "*/*"; myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)"; myHttpWebRequest.CookieContainer = cookies; //使用已经保存的cookies 方法一 //myHttpWebRequest.Headers.Add("Cookie", cookiesstr); //使用已经保存的cookies 方法二 HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); Stream stream = myHttpWebResponse.GetResponseStream(); stream.ReadTimeout = 15 * 1000; //读取超时 StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("utf-8")); string strWebData = sr.ReadToEnd(); richTextBox1.Text = cookiesstr +"\r\n\r\n"+ strWebData;
------------------------------------------------------- 未能为 SSL/TLS 安全通道建立信任的解决办法
在通过HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); 作处理时,有些输入有些URL会在HttpWebResponse sp = (HttpWebResponse)req.GetResponse();的时候抛出一个“基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系”的异常。 最简单的办法是: 1,先加入命名空间: using System.Net.Security; 2,再重载CheckValidationResult方法,返回true public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 3,然后在HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);前面加上如下一行代码: ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
|
请发表评论