【问题标题】:How to pass data to server using HttpClient in xamarin.android如何在 xamarin.android 中使用 HttpClient 将数据传递给服务器
【发布时间】:2017-08-29 08:45:27
【问题描述】:

我正在 xamarin 中开发一个 android 应用程序,现在我想发出 post 请求并将以下数据发送到服务器

Name 
EmailID
Prod_EMAILID
ID

并从服务器Link of API获得响应。我已经做了类似的事情

static async Task CallWebAPIAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:55587/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                

        //POST Method
        var post = new Post() { Id = 1,NAME="aaaaa222",PROF_EMAILD="aaa@gmail.com",MAILID="asasa@gmail.com" };
        HttpResponseMessage responsePost = await client.PostAsJsonAsync("api/Department", post);
        if (responsePost.IsSuccessStatusCode)
        {
            // Get the URI of the created resource.
            Uri returnUrl = responsePost.Headers.Location;
            Console.WriteLine(returnUrl);
        }        
    }
    Console.Read();    
}

但它只适用于 GET 方法,现在我想在 Httpclient 中发出 post 请求

【问题讨论】:

  • 我建议查看 restsharp.org 它可以连接到您的 API 并将 JSON 结果解析为 C# 对象
  • 我要使用HttpClient.如何实现
  • 您遇到了什么错误?
  • HttpClient 不包含 PostAsJsonAsync 的定义
  • 现在我收到类似 The name Encoading does not exist in current context 之类的错误

标签: c# post xamarin.android dotnet-httpclient


【解决方案1】:

这是我在解决方案中使用 HttpClient 的方式

using (var client = new HttpClient())
{
    var content = new StringContent(JsonConvert.SerializeObject(myPoco));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var response = await client.PostAsync(new Uri("http://your-url"), content);

    /* handle response here*/
};

myPoco 是你的普通 C# 对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多