Xamarin发送POST数据

时间:2018-05-14 15:23:16

标签: c# xamarin

我正在尝试将POST数据发送到我的服务器并获得响应。出于某种原因,实际上没有发送POST数据。正在向我的服务器发送请求,但POST数组为空。

以下是我发送请求的代码:

public class GlobalMethods
{
    public async Task<string> callAjax(string mthd,NameValueCollection parameters)
    {
        var client = new HttpClient();
        var content = JsonConvert.SerializeObject(parameters);

        var result = await client.PostAsync("http://dev.adex-intl.com/adex/mvc/receiving/"+mthd, new StringContent(content)).ConfigureAwait(false);
        var tokenJson = "";

        if (result.IsSuccessStatusCode)
        {
            tokenJson = await result.Content.ReadAsStringAsync();
        }
        return tokenJson;
    }
}

这是我调用上述方法的代码:

public void loginPressed(object sender, EventArgs e)
    {
        if(String.IsNullOrEmpty(badge.Text)) {
            DisplayAlert("Error", "Enter your badge number", "Ok");
        } else {
            IsBusy = true;
            NameValueCollection parameters = new NameValueCollection();
            parameters["badgetNumber"] = badge.Text;
            GlobalMethods globalMethods = new GlobalMethods();
                var results = globalMethods.callAjax("login", parameters);
        }
    }

我不确定我做错了什么。另外,我是Xamarin和C#的新手,所以我甚至不确定我尝试做事的方式是否是最佳方式。

2 个答案:

答案 0 :(得分:2)

您还没有指定要发送的内容类型,在您的情况下是'application / json',您可以这样设置:  “var client = new HttpClient(); var content = new StringContent(JsonConvert.SerializeObject(parameters)); content.Headers.ContentType = new MediaTypeHeaderValue("application/json");”。另外,我建议你写这样的代码:

 var uri = new Uri(url);
 using (var body = new StringContent(JsonConvert.SerializeObject(data)))
 {
    body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var request = new HttpRequestMessage
    {
       Version = new Version(1, 0),
       Content = body,
       Method = HttpMethod.Post,
       RequestUri = uri
    };

    try
    {
        using (var response = await _client.SendAsync(request,cancellationToken))
        {
           if (response.IsSuccessStatusCode)
           {
              //Deal with success response
           }
           else
           {
              //Deal with non-success response
           }               
        }
    }
    catch(Exception ex)
    {
        //Deal with exception.
    }
 }

答案 1 :(得分:0)

您可以使用PostAsync异步向服务器发送数据。你的代码应该是这样的:

HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
   { "p1", "data1" },
   { "p2", "data2" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/index.php", content);
var responseString = await response.Content.ReadAsStringAsync();