How to use credentials in HttpClient in c#?

前端 未结 3 905
滥情空心
滥情空心 2020-12-06 09:38

I am facing some problems when using the HttpClient class to access to a Delicious API. I have the following code:

try
{
    const string uriSources = \"http         


        
3条回答
  •  一整个雨季
    2020-12-06 10:10

    I had the exact same problem myself. It seems the HttpClient just disregards the credentials set in the HttpClientHandler.

    The following shall work however:

    using System.Net.Http.Headers; // For AuthenticationHeaderValue
    
    const string uri = "https://example.com/path?params=1";
    using (var client = new HttpClient()) {
        var byteArray = Encoding.ASCII.GetBytes("MyUSER:MyPASS");
        var header = new AuthenticationHeaderValue(
                   "Basic", Convert.ToBase64String(byteArray));
        client.DefaultRequestHeaders.Authorization = header;
    
        var result = await client.GetStringAsync(uri);
    }
    

    No need for the handler.

    Source: http://www.snip2code.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us

提交回复
热议问题