c#獲取url請求的返回值
阿新 • • 發佈:2017-05-09
web c# new mar string htm http class dto
- /// <summary>
- /// 獲取url的返回值
- /// </summary>
- /// <param name="url">eg:http://m.weather.com.cn/atad/101010100.html </param>
- public string GetInfo(string url)
- {
- string strBuff = "";
- Uri httpURL = new Uri(url);
- ///HttpWebRequest類繼承於WebRequest,並沒有自己的構造函數,需通過WebRequest的Creat方法 建立,並進行強制的類型轉換
- HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
- ///通過HttpWebRequest的GetResponse()方法建立HttpWebResponse,強制類型轉換
- HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
- ///GetResponseStream()方法獲取HTTP響應的數據流,並嘗試取得URL中所指定的網頁內容
- ///若成功取得網頁的內容,則以System.IO.Stream形式返回,若失敗則產生ProtoclViolationException錯 誤。在此正確的做法應將以下的代碼放到一個try塊中處理。這裏簡單處理
- Stream respStream = httpResp.GetResponseStream();
- ///返回的內容是Stream形式的,所以可以利用StreamReader類獲取GetResponseStream的內容,並以
- //StreamReader類的Read方法依次讀取網頁源程序代碼每一行的內容,直至行尾(讀取的編碼格式:UTF8)
- StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
- strBuff = respStreamReader.ReadToEnd();
- return strBuff;
- }
or
- /// <summary>
- /// Get方式獲取url地址輸出內容
- /// </summary> /// <param name="url">url</param>
- /// <param name="encoding">返回內容編碼方式,例如:Encoding.UTF8</param>
- public static String SendRequest(String url,Encoding encoding)
- {
- HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
- webRequest.Method = "GET";
- HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
- StreamReader sr = new StreamReader(webResponse.GetResponseStream(), encoding);
- return sr.ReadToEnd();
- }
c#獲取url請求的返回值