方式一  

  

 

        string strResult = string.Empty;
        HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create("http://xxxxx/checkpower.aspx");
        string postdata = "v_objectid=" + Objectid.ToString() + "&v_website=" + website + "&v_useracc=" + useracc;
        byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(postdata);
        myReq.Method = "POST";
        myReq.Proxy = null;    //framework 2.0 默认搜索代理 所以把它关闭 据称能省掉不少搜索代理的时间
        myReq.ContentType = "application/x-www-form-urlencoded";
        myReq.ContentLength = requestBytes.Length;
        Stream requeststream = myReq.GetRequestStream();
        requeststream.Write(requestBytes, 0, requestBytes.Length);
        requeststream.Close();

 

    //到这里为止 异步信息已经发出去了  如果不需要返回值  可以不需执行下面的步骤

    //下面为返回服务器异步的信息

 

        HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
        Stream myStream = HttpWResp.GetResponseStream();
        StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
          strResult = sr.ReadToEnd(); //读取完整内容
        sr.Close();  //释放StreamReader 以防html读取不完全的状况
        sr.Dispose();  //释放StreamReader 以防html读取不完全的状况

    Response.Write(strResult);      

    

  //如果要追踪远端页面的错误,则可使用以下方式

   HttpWebResponse HttpWResp;

        try
        {
            HttpWResp = (HttpWebResponse)myReq.GetResponse();

        }
        catch (WebException ext)
        {
            HttpWResp = (HttpWebResponse)ext.Response;
        }

   //则返回的信息中包含对方页面的错误提示

 

方法二

 

 

    private WebRequest _request;
    protected void Page_Load(object sender, EventArgs e)
    {

        AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));

    }

    public IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        _request = WebRequest.Create("http://xxxxxx/test1.asp");
        return _request.BeginGetResponse(cb, state);
    }

    void EndAsyncOperation(IAsyncResult ar)
    {
        using (WebResponse Wresponse = _request.EndGetResponse(ar))
        {
            using (StreamReader reader = new StreamReader(Wresponse.GetResponseStream(), Encoding.GetEncoding("BIG5")))
            {
                string temp_str = reader.ReadToEnd();
                Response.Write(temp_str);
                Response.End();
            }
        }
    }

 

 

  在各种不同的情况下选择异步的方式

 

 --------------------------------------------------------------------------------------------------------------------------------------------------

有时候会需要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);

 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "GET";           

            HttpWebResponse sp = (HttpWebResponse)req.GetResponse();

作处理时,有些输入有些URL会在HttpWebResponse sp = (HttpWebResponse)req.GetResponse();的时候抛出一个“基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系”的异常。

最简单的办法是:

1,先加入命名空间:

using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

2,再重载CheckValidationResult方法,返回true

public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {   // 总是接受  
        return true;
    }

3,然后在HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);前面加上如下一行代码:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证 

 

 

 

 posted on 2009-11-30 18:26  vingi_苍月  阅读(621)  评论(0编辑  收藏  举报