如何在 Xamarin 中发送 POST 请求? [英] How to send POST request in Xamarin?

查看:75
本文介绍了如何在 Xamarin 中发送 POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've built my backend in rails. My email address is "sample@zmail.com" and it's already registered. The password is "28902890" here

在终端输入以下命令后

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\"}}"

我从我的后端得到这个回复,

I get this response from my backend,

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

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

Now I need to get this data from my Android app. I can get json by using WebClient().downloadString() method for simple json where authentication is not needed and the request method is GET.

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

Now I need to get the output Json for POST method. How can I accomplish that?

推荐答案

我是这样做的:

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

这篇关于如何在 Xamarin 中发送 POST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆