Reza Reza - 1 year ago 753
Android Question

How to send POST request in Xamarin?

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

After giving the following command in terminal

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d "{\"user\":{\"email\":\"sample@zmail\",\"password\":\"28902890\"}}"

I get this response from my backend,

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

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.

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

Answer Source

This is how I did it:

  WebClient wc = new WebClient();
        string baseSiteString = wc.DownloadString("");
        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"":"""",""password"":""28902890""}}";
     //   string dataString = @"{""user"":{""email"":"""+uEmail+@""",""password"":"""+uPassword+@"""}}";
        byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
        byte[] responseBytes = wc.UploadData(new Uri(""), "POST", dataBytes);
        string responseString = Encoding.UTF8.GetString(responseBytes);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download