简体   繁体   English

Xamarin Android HttpClient PostAsync

[英]Xamarin Android HttpClient PostAsync

I have an android app in Xamarin native. 我在Xamarin本机中有一个android应用。 I am trying to consume a Restful service from an API in another server. 我正在尝试从另一台服务器的API中使用Restful服务。

I have this: 我有这个:

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;
            }
        }

I execute this on a button call like this: 我在这样的按钮调用上执行此操作:

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);                
        }

But when my code gets to the postAsync method, nothing happens, it just continues without actually sending the code to the endpoint, I have no idea what I might be doing wrong, because all documentation I have on PostAsync tells me this is how to send json data for a Restful Web api endpoint. 但是,当我的代码进入postAsync方法时,什么也没有发生,它只是继续运行而没有将代码实际发送到端点,我不知道自己可能做错了什么,因为我在PostAsync上拥有的所有文档都告诉我这是如何发送的Restful Web api端点的json数据。

Thank you in advance for any pointers. 预先感谢您提供任何指导。

You need to await the call to CreateCellphone or nothing will happen because the response Task will get disposed of almost immediately. 您需要awaitCreateCellphone的调用,否则将不会发生任何事情,因为response Task将几乎立即被处理掉。 Not sure if you can make your button click method async in Xamarin, but I would try this: 不知道是否可以在Xamarin中使按钮单击方法async ,但是我会尝试这样做:

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

    await CreateCellphone(_url, cell);
}

Failing that, there are various way to call an async method synchronously, check this question . 如果失败,有多种方法可以同步调用异步方法,请检查此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM