資料來源
http://itgroup.blueshop.com.tw/cwvdavid/pg?n=convew&i=247135
Public Function ConnectUrl_andGetText(ByVal MyUrl As String) As String '連到指定網頁, 並將文字內容抓回來顯示... 'HttpUtility.UrlEncode("") Dim MyHtmlData As String = "" Dim myRequest As System.Net.WebRequest 'Request Dim myResponse As System.Net.WebResponse 'Response Dim myStream As System.IO.StreamReader '利用StreamReader讀取資料 Dim ContentLength As Long = 0 Dim LocalFile As System.IO.FileStream Try myRequest = System.Net.WebRequest.Create(MyUrl) myResponse = myRequest.GetResponse() ContentLength = myResponse.ContentLength 'ContentLength = -1 If ContentLength >= 0 Then '(以UTF8來讀取) myStream = New System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8) '資料讀取到字串變數中...直接整個讀取 '(遇到網路不穩時容易出問題) '(遇到ContentLength未知時, 一定出問題...) MyHtmlData = myStream.ReadToEnd() Else '如果ContentLength小於0, 就必須另外處理, '看是要先下載, 另存成文字檔, 再讀取 '或是其他方式... Dim Buffer As Byte() = New Byte(2047) {} Dim 暫存位置 As String = Environment.GetEnvironmentVariable("temp") & "\SFCS_TempUrlFile.Text" Dim BytesRead As Long LocalFile = New IO.FileStream(暫存位置, IO.FileMode.Create) 'Create the local file Do BytesRead = myResponse.GetResponseStream().Read(Buffer, 0, 2048) LocalFile.Write(Buffer, 0, BytesRead) Loop Until BytesRead = 0 LocalFile.Flush() LocalFile.Close() myStream = New System.IO.StreamReader(暫存位置, System.Text.Encoding.UTF8) MyHtmlData = myStream.ReadToEnd End If Catch ex As Exception MyHtmlData = "Url讀取錯誤:" & MyUrl & " " & ex.Message End Try '關閉FileStream If Not LocalFile Is Nothing Then LocalFile.Close() End If '關閉StreamReader If Not myStream Is Nothing Then myStream.Close() End If '關閉連線 If Not myResponse Is Nothing Then myResponse.Close() End If Return MyHtmlData '這是要回傳的內容... End Function
文章標籤
全站熱搜
留言列表