VB.NET中的HTTP GET

not*_*ndy 37 vb.net http-get

在VB.net中发布http get的最佳方法是什么?我想得到一个请求的结果,如http://api.hostip.info/?ip=68.180.206.184

han*_*ngy 67

在VB.NET中:

Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")
Run Code Online (Sandbox Code Playgroud)

在C#中:

System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");
Run Code Online (Sandbox Code Playgroud)

  • `Dim webClient As System.Net.WebClient = New System.Net.WebClient()` 可以缩写为`Dim webClient As New System.Net.WebClient` 不是吗? (2认同)
  • @Matt 使用 [`HttpWebRequest`](http://stackoverflow.com/a/92588/11963) 并设置 [`Credentials`](http://msdn.microsoft.com/library/system.net.httpwebrequest. credentials.aspx) 属性添加到 [`NetworkCredential`](http://msdn.microsoft.com/library/system.net.networkcredential.aspx) 的新实例。 (2认同)

Wol*_*yrd 23

您可以使用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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

有关webclient的更多信息,请访问:http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx


chr*_*ie1 5

使用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
Run Code Online (Sandbox Code Playgroud)