简体   繁体   English

带有身份验证的 VB.Net HttpClient GET 请求

[英]VB.Net HttpClient GET request with authentication

I have this snippet of code that I am wanting to use as a base for a call I need to make to a REST API GET request to return JSON data.我有这段代码,我想将其用作调用的基础,我需要对 REST API GET 请求进行调用以返回 JSON 数据。 I am able to call this and works fine.我可以调用它并且工作正常。 Now I am wanting to plug in the website I need.现在我想插入我需要的网站。 However, the site requires a username/password that I have.但是,该站点需要我拥有的用户名/密码。 I just do not know exactly how to implement it in this situation.我只是不知道在这种情况下如何实现它。 I am used to using WebRequest but saw it was recommended to use HttpClient.我习惯使用WebRequest,但看到建议使用HttpClient。

Sub Main()
        ' Create new Task.
        ' ... Use AddressOf to reference a method.
        Dim t As Task = New Task(AddressOf DownloadPageAsync)
        ' Start the task.
        t.Start()
        ' Print a message as the page downloads.
        Console.WriteLine("Downloading page...")
        Console.ReadLine()
    End Sub

    Async Sub DownloadPageAsync()
        Dim page As String = "http://en.wikipedia.org/"

        ' Use HttpClient in Using-statement.
        ' ... Use GetAsync to get the page data.
        Using client As HttpClient = New HttpClient()
            Using response As HttpResponseMessage = Await client.GetAsync(page)
                Using content As HttpContent = response.Content
                    ' Get contents of page as a String.
                    Dim result As String = Await content.ReadAsStringAsync()
                    ' If data exists, print a substring.
                    If result IsNot Nothing And result.Length > 50 Then
                        Console.WriteLine(result.Substring(0, 50) + "...")
                    End If
                End Using
            End Using
        End Using
    End Sub

Here's a code example from the documentation for the HttpClientHandler class:以下是HttpClientHandler类文档中的代码示例:

static async Task Main()
{
   // Create an HttpClientHandler object and set to use default credentials
   HttpClientHandler handler = new HttpClientHandler();
   handler.UseDefaultCredentials = true;

   // Create an HttpClient object
   HttpClient client = new HttpClient(handler);

   // Call asynchronous network methods in a try/catch block to handle exceptions
   try
   {
      HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");

      response.EnsureSuccessStatusCode();

      string responseBody = await response.Content.ReadAsStringAsync();
      Console.WriteLine(responseBody);
   }
   catch(HttpRequestException e)
   {
       Console.WriteLine("\nException Caught!");
       Console.WriteLine("Message :{0} ",e.Message);
   }

   // Need to call dispose on the HttpClient and HttpClientHandler objects
   // when done using them, so the app doesn't leak resources
   handler.Dispose();
   client.Dispose();
}

In this case, it is using the system default credentials but you can create a NetworkCredential yourself if you need to.在这种情况下,它使用系统默认凭据,但如果需要,您可以自己创建NetworkCredential That means that, in your code, you could change this:这意味着,在您的代码中,您可以更改此内容:

Using client As HttpClient = New HttpClient()
    '...
End Using

to something like this:像这样:

Using handler As New HttpClientHandler With {.Credentials = New NetworkCredential(username, password)},
      client As New HttpClient(handler)
    '...
End Using

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM