2

This works:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.Authorization] = "Basic " + base64;
client.DownloadStringCompleted += getAccessToken_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(URL));

However, i need to move it to HttpClient (because i've started using Portable Class Library), so i got this:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64);

string response = await client.GetStringAsync(URL); 

But here the HttpClient fails in the surrounding try/catch saying

Response status code does not indicate success: 400 (Bad Request).

I don't really see any diff....? What might be the problem?

Jason94
  • 13,320
  • 37
  • 106
  • 184
  • 4
    Check with Fiddler if both requests are send with the same Authorization header. – Alexei Levenkov Nov 27 '13 at 20:35
  • have you tried using client.Credentials instead of headers – maxlego Nov 27 '13 at 21:48
  • see http://stackoverflow.com/questions/10077237/httpclient-authentication-header-not-getting-sent – wal Nov 27 '13 at 21:51
  • The code you are showing is fine. What is weird is that HttpClient doesn't throw errors when it receives a 400. Is there other code you are not showing? – Darrel Miller Nov 27 '13 at 23:27
  • @Darrel Miller, by fails i mean throws... it throws into the catch with the error i posted :-) – Jason94 Nov 28 '13 at 08:04
  • @Jason94 Yeah, I forgot that the GetXXXAsync helper methods call EnsureSuccessStatusCode internally. Calling GetAsync or SendAsync do not throw on Bad request. – Darrel Miller Nov 28 '13 at 14:17
  • I'm seeing the same thing when using the portable HttpClient in a Xamarin.iOS app. I'm occasionally getting a 400 when requesting a resource that the current requester doesn't have access to (it's a third-party service I don't have control over). But I'm EXPECTING this 400 status code in some cases and want to handle it. However, some logic in the HttpClient isn't throwing an exception as I would expect. It just crashes natively. Weird. – NovaJoe Apr 07 '14 at 20:29

0 Answers0