一般在家中上網,不會設定什麼Proxy,

但公司通常會透過Proxy連結外部網站,

這時,若該網站又需要存取的Proxy為要求的信任連線(認證)時,

未設定Proxy則會出現錯誤,這時要設定WebProxy如下:

方法1
//讀取IE的Proxy設定
this.m_objProxy = WebProxy.GetDefaultProxy();
//目前登入之使用者的認證
this.m_objProxy.UseDefaultCredentials = true;

方法2
//直接設定Proxy,語法可參考DOT NET
this.m_objProxy = new WebProxy(@"Proxy.XXXX.com.tw", false);

 

範例程式碼

        /// <summary>
        /// 載入網頁
        /// </summary>
        public bool LoadWebPage()
        {
            WebRequest objWebReq = null;
            HttpWebResponse objWebRep = null;
            StreamReader objReader = null;
            WebClient objWebClient = null;

            try
            {

                //讀取IE的Proxy設定
                this.m_objProxy = WebProxy.GetDefaultProxy();
                //目前登入之使用者的認證
                this.m_objProxy.UseDefaultCredentials = true;
               
                objWebReq = HttpWebRequest.Create(this.m_strURL.Trim());
                //連公司連出去需要透過Proxy,故要設定
                objWebReq.Proxy = this.m_objProxy;

                //這行會因公司的Proxy有問題,故要做以上設定以利Proxy通過
                objWebRep = (HttpWebResponse)objWebReq.GetResponse();

                Encoding encoding = Encoding.GetEncoding(objWebRep.CharacterSet);
                objReader = new StreamReader(objWebRep.GetResponseStream(), encoding);
                string strContent = objReader.ReadToEnd();

                return true;
            }
            finally
            {
                objReader.Close();
                objWebRep.Close();
            }
        }

arrow
arrow
    全站熱搜

    張小橘 發表在 痞客邦 留言(1) 人氣()