1. 程式人生 > >c#獲取url請求的返回值

c#獲取url請求的返回值

web c# new mar string htm http class dto

  1. /// <summary>
  2. /// 獲取url的返回值
  3. /// </summary>
  4. /// <param name="url">eg:http://m.weather.com.cn/atad/101010100.html </param>
  5. public string GetInfo(string url)
  6. {
  7. string strBuff = "";
  8. Uri httpURL = new Uri(url);
  9. ///HttpWebRequest類繼承於WebRequest,並沒有自己的構造函數,需通過WebRequest的Creat方法 建立,並進行強制的類型轉換
  10. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
  11. ///通過HttpWebRequest的GetResponse()方法建立HttpWebResponse,強制類型轉換
  12. HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
  13. ///GetResponseStream()方法獲取HTTP響應的數據流,並嘗試取得URL中所指定的網頁內容
  14. ///若成功取得網頁的內容,則以System.IO.Stream形式返回,若失敗則產生ProtoclViolationException錯 誤。在此正確的做法應將以下的代碼放到一個try塊中處理。這裏簡單處理
  15. Stream respStream = httpResp.GetResponseStream();
  16. ///返回的內容是Stream形式的,所以可以利用StreamReader類獲取GetResponseStream的內容,並以
  17. //StreamReader類的Read方法依次讀取網頁源程序代碼每一行的內容,直至行尾(讀取的編碼格式:UTF8)
  18. StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
  19. strBuff = respStreamReader.ReadToEnd();
  20. return strBuff;
  21. }

or

  1. /// <summary>
  2. /// Get方式獲取url地址輸出內容
  3. /// </summary> /// <param name="url">url</param>
  4. /// <param name="encoding">返回內容編碼方式,例如:Encoding.UTF8</param>
  5. public static String SendRequest(String url,Encoding encoding)
  6. {
  7. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  8. webRequest.Method = "GET";
  9. HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
  10. StreamReader sr = new StreamReader(webResponse.GetResponseStream(), encoding);
  11. return sr.ReadToEnd();
  12. }

c#獲取url請求的返回值