【发布时间】:2017-02-14 10:49:08
【问题描述】:
我是初学者,我使用一个 Xamarin 应用程序。 我尝试将我的应用程序连接到一个 Https 服务器以获取令牌,当我测试与 Postman 的连接时,一切正常。但对于我的应用程序,则是另一回事了..
网络服务是:aps.net-web-api-2
这是我在 Xamarin 中的连接代码:
using System.Net.Http;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.getButton);
button.Click += async (sender, e) =>
{
try
{
string url = "https://urlexample/foo/bar/Token";
string values = await RequestWeb(url);
}
catch (Exception ex)
{
Log.Info("error with click", ex.ToString());
}
};
}
private async Task<string> RequestHttps(string url)
{
string responseString = string.Empty;
using (HttpClient client = new HttpClient())
{
Dictionary<string,string> values = new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "username", "User1" },
{ "password", "123456" }
};
FormUrlEncodedContent content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync(url, content);
responseString = await response.Content.ReadAsStringAsync();
}
return responseString;
}
当我使用我的代码进行测试时,我使用 Try and Catch 恢复了我的异常:
I/error with click(14476): System.Net.WebException: Error: TrustFailure (The authentication or decryption has failed.)
问题来自这一行:
HttpResponseMessage response = await client.PostAsync(url, content);
以邮递员为例,对于这个连接,我得到一个连接令牌:
Post -> Headers
- Content_type : application/x-www-form-urlencoded
- grand_type : password
- username : User1
- password : 123456
结果:
{ "access_token": "ATT4U2xGQqsdf", "token_type": "bearer", "expires_in": 15 }
我也尝试其他连接方式 (example here) 而且我想知道,当我阅读适用于 Android 的课程 (here) 时,据说不要使用线程 UI 创建连接,而是使用另一个线程。 但是我发现很多例子都没有使用线程 UI,为什么? 还是我误解了一件事?
我也想知道问题是否来自我的设置?
或者也许我完全迷路了......(哈哈)。
最好的问候, 罗曼
【问题讨论】:
标签: c# android xamarin https asp.net-web-api2