![](/img/trans.png)
[英]Xamarin.Android HttpClient PostAsync gets cancelled when in Release
[英]Xamarin Android HttpClient PostAsync
我在Xamarin本机中有一个android应用。 我正在尝试从另一台服务器的API中使用Restful服务。
我有这个:
private async Task<string> CreateCellphone(string url, Cellphone cell)
{
string cellphone = JsonConvert.SerializeObject(cell);
HttpContent content = new StringContent(cellphone, Encoding.UTF8, "application/json");
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(url, content);
string responseMessage = await response.Content.ReadAsStringAsync();
return responseMessage;
}
}
我在这样的按钮调用上执行此操作:
private void RegisterButtonOnClick(object sender, EventArgs e)
{
// Create new GUID
Guid obj = Guid.NewGuid();
// Store the created GUID in a private shared preferences file
var localGUID = Application.Context.GetSharedPreferences("LocalSetup", FileCreationMode.Private);
var guidEdit = localGUID.Edit();
guidEdit.PutString("GUID", obj.ToString());
guidEdit.PutBoolean("IsRegistered", true);
guidEdit.Commit();
// Create the cellphone record into the database for DB admin to activate
_url = Resources.GetString(Resource.String.cellphone_api_url);
Cellphone cell = new Cellphone();
cell.CellphoneId = obj.ToString();
var response = CreateCellphone(_url, cell);
}
但是,当我的代码进入postAsync方法时,什么也没有发生,它只是继续运行而没有将代码实际发送到端点,我不知道自己可能做错了什么,因为我在PostAsync上拥有的所有文档都告诉我这是如何发送的Restful Web api端点的json数据。
预先感谢您提供任何指导。
您需要await
对CreateCellphone
的调用,否则将不会发生任何事情,因为response
Task将几乎立即被处理掉。 不知道是否可以在Xamarin中使按钮单击方法async
,但是我会尝试这样做:
private async void RegisterButtonOnClick(object sender, EventArgs e)
//^^^^^
//Add this
{
//snip
await CreateCellphone(_url, cell);
}
如果失败,有多种方法可以同步调用异步方法,请检查此问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.