简体   繁体   中英

How to send POST request in Xamarin?

I've built my backend in rails. My email address is "sample@zmail.com" 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 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"}}

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?

There are several methods of doing this. You could use the Xamarin component called RestSharp . This will provide you with easy methods of interfacing with your backend.

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

If you do want to simply use the WebClient class provided by the BCL you can use the WebClient.UploadString(string, string) method like so:

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

If you need more control over the request (such as setting accept headers, etc.) then you can use HttpRequest , see this question for an example of that.

This is how I did it:

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

Try with this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM