Xamarin Android HttpClient PostAsync

时间:2017-07-21 15:20:29

标签: c# post xamarin.android httpclient

我有一个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数据。

提前感谢您的任何指示。

1 个答案:

答案 0 :(得分:1)

您需要awaitCreateCellphone的调用,否则不会发生任何事情,因为response任务几乎会立即被处理掉。不确定你是否可以在Xamarin中点击方法async,但我会试试这个:

private async void RegisterButtonOnClick(object sender, EventArgs e)
      //^^^^^
      //Add this
{
    //snip

    await CreateCellphone(_url, cell);
}

如果失败,有多种方法可以同步调用异步方法,请检查this question