在VB.net中发出http get的最佳方式是什么?我想要得到像http://api.hostip.info/?ip=68.180.206.184这样的请求的结果
发布于 2008-09-18 13:31:46
在VB.NET中:
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")
在C#中:
System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");
发布于 2008-09-18 13:37:27
您可以使用HttpWebRequest类执行请求并从给定的URL检索响应。您将像这样使用它:
Try
Dim fr As System.Net.HttpWebRequest
Dim targetURI As New Uri("http://whatever.you.want.to.get/file.html")
fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
If (fr.GetResponse().ContentLength > 0) Then
Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
Response.Write(str.ReadToEnd())
str.Close();
End If
Catch ex As System.Net.WebException
'Error in accessing the resource, handle it
End Try
有关HttpWebRequest的详细信息,请访问http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
第二种选择是使用WebClient类,这为下载web资源提供了一个更容易使用的接口,但没有HttpWebRequest那么灵活:
Sub Main()
'Address of URL
Dim URL As String = http://whatever.com
' Get HTML data
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
End Sub
有关网络客户端的更多信息,请访问:http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
发布于 2008-09-18 13:32:26
使用WebRequest类
这是为了得到一张图片:
Try
Dim _WebRequest As System.Net.WebRequest = Nothing
_WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)
Catch ex As Exception
Windows.Forms.MessageBox.Show(ex.Message)
Exit Sub
End Try
Try
_NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())
Catch ex As Exception
Windows.Forms.MessageBox.Show(ex.Message)
Exit Sub
End Try
https://stackoverflow.com/questions/92522
复制相似问题