Xamarin Android HttpClient PostAsync

问题描述:

我有一个Xamarin原生的Android应用程序。我试图从另一台服务器的API中使用Restful服务。Xamarin Android HttpClient PostAsync

我有这样的:

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方法,没有任何反应,只是继续不实际:

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

我上的一个按钮呼叫这样执行此将代码发送到端点,我不知道我可能会做错什么,因为我在PostAsync上的所有文档都告诉我这是如何为Restful Web api端点发送json数据。

预先感谢您的任何指针。

您需要await致电CreateCellphone,否则什么都不会发生,因为response任务将立即被处置。不知道如果你可以让你按一下按钮方法async在Xamarin,但我会尝试这个办法:

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

    await CreateCellphone(_url, cell); 
} 

做不到这一点,有各种方式来同步调用异步方法,检查this question

+0

我习惯了异步方法,现在我只是对实际的请求执行异步操作,它就像一个魅力,谢谢! –