0

I am trying to send a HTTP GET request to a service secured with BASIC authentication and https. If I use the RESTClient Firefox plugin to do so there is no problem. I am defining the basic-header and sending the GET to the url and I am getting the answer (data in json).

Now I am working on a Windows Store App in C# which is meant to consume the service. I enabled all required capabilities in the manifest and wrote the following method:

private async void HttpRequest()
        {
            string basic = "Basic ...........";

            Uri testuri = new Uri(@"https://...Servlet");

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", basic);

            Task<HttpResponseMessage> response = client.GetAsync(testuri);
            var text = await response;
            var message = text.RequestMessage;
        }

I tried out many different possibilites like getting the response-string but everything lead to an 401 Status Code answer from the Server.

I looked at many similar problems and my understanding of the communication is the following: Client request -> Server response with 401 -> Client sends Authorization header -> Server response with 200 (OK)

What I don't understand is why I am getting the 401 "Unauthorized" Status Code although I am sending the Authorization header right at the beginning. It would be interesting if someone knows how this is handled in the RESTClient.

The BASIC header is definetly correct I was comparing it with the one in the RESTClient.

It would be great if someone could help me with this.

Thanks in advance and kind regards, Max

leppie
  • 115,091
  • 17
  • 196
  • 297
Eisleyy
  • 1
  • 1
  • 1
  • 1
    Interesting... after many tries I finally found the solution which I don't really understand. Working with CredentialCache instead of the own auth-header or the standard Credential-class solved the problem. – Eisleyy May 31 '13 at 14:56

2 Answers2

6

Was having a similar problem, i added a HttpClientHandler to HttpClient.

var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("","")
var httpClient = new HttpClient(httpClientHandler);
XS_iceman
  • 161
  • 1
  • 6
1

Credentials should be encoded, before adding to the header. I tested it in WPF app, It works...

      string _auth = string.Format("{0}:{1}", "username", "password");
      string _enc = Convert.ToBase64String(Encoding.UTF8.GetBytes(_auth));
      string _basic = string.Format("{0} {1}", "Basic", _enc);

      HttpClient client = new HttpClient();
      client.DefaultRequestHeaders.Add("Authorization",_basic);
Adarsh Urs
  • 112
  • 8