[英]HttpClient not accepting Authorization headers (401 Unauthorized)?
I am creating a Xamarin.Forms mobile app that targets Android with .NET Standard as my code sharing method.我正在创建一个 Xamarin.Forms 移动应用程序,它以 .NET Standard 作为我的代码共享方法的 Android 为目标。 Unfortunately the API I'm consuming works in Postman but doesn't work in C# using HttpClient from System.Net.Http.
不幸的是,我正在使用的 API 在 Postman 中有效,但在使用 System.Net.Http 的 HttpClient 的 C# 中无效。
Postman request works using this header:邮递员请求使用此标头工作:
I have tried 3 different approaches but they all still return "401 unauthorized".我尝试了 3 种不同的方法,但它们仍然返回“401 未授权”。 I've also checked the INTERNET permission in my Android Manifest file.
我还检查了我的 Android 清单文件中的 INTERNET 权限。
HttpClient.DefaultRequestHeaders.Add("Authorization", "Token e2eeb1aa9f32eb0ekgn353b6fadb772");
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "e2eeb1aa9f32eb0ekgn353b6fadb772");
HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Token e2eeb1aa9f32eb0ekgn353b6fadb772");
Please make sure your HTTP request URL is correct or not.请确保您的 HTTP 请求URL正确与否。 Sometimes you may need a trailing backslash ( '/' ).
有时您可能需要尾随反斜杠( '/' )。 If you missed it in HTTP client , will not work but POSTMAN will .
如果您在HTTP 客户端中错过了它,它将不起作用,但POSTMAN会。
Try setting the header on the HttpRequestMessage
:尝试在
HttpRequestMessage
上设置标头:
request.Headers.Authorization = new
AuthenticationHeaderValue("Bearer","e2eeb1aa9f32eb0ekgn353b6fadb772");
In my case, was fixed when I set the basic authentication in the AuthenticationHeaderValue.就我而言,在 AuthenticationHeaderValue 中设置基本身份验证时已修复。
var authToken = Encoding.ASCII.GetBytes(_UserName + ":" + _Password);
client.DefaultRequestHeaders.Authorization= new AunthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.