【问题标题】:How to send POST request in Xamarin?如何在 Xamarin 中发送 POST 请求?
【发布时间】:2018-11-06 20:23:39
【问题描述】:

我已经在 Rails 中构建了我的后端。 我的电子邮件地址是“sample@zmail.com”,并且已经注册。这里的密码是“28902890”

在终端输入以下命令后

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://auth-agdit.herokuapp.com/api/v1/sessions -d "{\"user\":{\"email\":\"sample@zmail\",\"password\":\"28902890\"}}"

我从后端收到此响应,

{"success":true,"info":"Logged in :) ","data":{"authentication_token":"iexGFwJ6HwERQZ3wJ4NG"}}

现在我需要从我的 Android 应用中获取这些数据。 对于不需要身份验证且请求方法为 GET 的简单 json,我可以使用 WebClient().downloadString() 方法获取 json。

现在我需要为 POST 方法获取输出 Json。 我怎样才能做到这一点?

【问题讨论】:

    标签: c# android xamarin xamarin.android


    【解决方案1】:

    有几种方法可以做到这一点。您可以使用名为 RestSharp 的 Xamarin 组件。这将为您提供与后端交互的简单方法。

    var request = new RestRequest("resource/{id}", Method.POST);
    request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
    request.AddUrlSegment("id", 123); // replaces matching token in request.Resource
    
    // add parameters for all properties on an object
    request.AddObject(object);
    
    // execute the request
    RestResponse response = client.Execute(request);
    

    如果您确实想简单地使用 BCL 提供的 WebClient 类,您可以使用 WebClient.UploadString(string, string) 方法,如下所示:

    using (WebClient client = new WebClient())
    {
      string json = "{\"user\":{\"email\":\"sample@zmail\",\"password\":\"28902890\"}}";
      client.UploadString("https://example.com/api/v1/sessions, json);
    }
    

    如果您需要对请求进行更多控制(例如设置接受标头等),则可以使用HttpRequest,有关示例,请参阅this question

    【讨论】:

    • 这有效,但只有在我添加了 'client.Headers[HttpRequestHeader.ContentType] = "application/json";'在 UploadString() 之前
    【解决方案2】:

    我就是这样做的:

      WebClient wc = new WebClient();
            string baseSiteString = wc.DownloadString("https://auth-agdit.herokuapp.com");
            string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
            string cookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie];
            Console.WriteLine("CSRF Token: {0}", csrfToken);
            Console.WriteLine("Cookie: {0}", cookie);
    
            wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
            wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
            wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
            wc.Headers.Add("X-CSRF-Token", csrfToken);
            wc.Headers.Add("X-Requested-With", "XMLHttpRequest");
    
    
            string dataString = @"{""user"":{""email"":""email_here"",""password"":""password_here""}}";
         //   string dataString = @"{""user"":{""email"":"""+uEmail+@""",""password"":"""+uPassword+@"""}}";
            byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
            byte[] responseBytes = wc.UploadData(new Uri("https://auth-agdit.herokuapp.com/api/v1/sessions.json"), "POST", dataBytes);
            string responseString = Encoding.UTF8.GetString(responseBytes);
            Console.WriteLine(responseString);
    

    【讨论】:

      【解决方案3】:

      试试这个代码:

      Uri address = new Uri("http://example.com/insert.php");
      NameValueCollection nameValueCollection = new NameValueCollection();
      nameValueCollection["Name"] = "string-input";
      
      var webClient = new WebClient();
      webClient.UploadValuesAsync(address, "POST", nameValueCollection);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 2021-01-09
        • 2017-11-17
        • 2015-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多