Search code examples
c#urldotnet-httpclient.net-4.5.2

HttpClient access url with '@' (at symbol)


I'm integrating a service that returns a key when I a GET request to a URL that is in the following format:

https://username:[email protected]/refresh.key

When I access the URL in my browser, it returns the new key as expected, by when I do a GET request using HttpClient I get a 401.

HttpClient _client = new HttpClient();
var response = await _client.GetAsync(@"https://username:[email protected]/refresh.key"); // Returns a 401

I think it has something to do with the '@' in the URL, but I'm not sure how to fix it, I tried replacing it with '%40', but when I do that I get a UriFormatException.

Does anyone know how to do this?


Solution

  • You should modify Authorization header of HttpClient, can you try the code below;

    HttpClient _client = new HttpClient();
    byte[] usernamePasswordBytes = Encoding.ASCII.GetBytes("user:pass");
    _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(usernamePasswordBytes));
    var response = await _client.GetAsync(@"https://service.com/refresh.key");
    

    PS: Such username:[email protected] requests are BasicAuthentication request so in fact you try to make basic authentication request.

    Hope this works for you