Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send HTTP Post request in Xamarin Forms C#

Before I start, I would like to say that I have googled solutions to this problem but have either not understood them (I am a newbie) or they do not work.

What I want to do is send JSON data to a REST API on localhost:8000, in this format:

{
    "username" : "myusername",
    "password" : "mypass"
}

Then, I expect a response which holds a string token, like the following,

{
    "token" : "rgh2ghgdsfds"
}

How do send the json data and then parse the token from the response? I have seen synchronous methods of doing this but for some reason, they do not work (or simply because I do not know what namespace it is in). If you apply an async way of doing this, could you please explain to me how it works?

Thanks in advance.

like image 839
alexcons Avatar asked Apr 06 '16 17:04

alexcons


People also ask

How do I post data in xamarin form?

To send data to the server you use the HTTP form data and send the parameters as form url encoded using the FormUrlEncodedContent class. The parameters will be sent as key/value pairs. We use the PostAsync method of the HttpClient class.

How to POST data using HttpClient in c#?

C# HttpClient POST form data var url = "https://httpbin.org/post"; using var client = new HttpClient(); var data = new Dictionary<string, string> { {"name", "John Doe"}, {"occupation", "gardener"} }; var res = await client. PostAsync(url, new FormUrlEncodedContent(data)); var content = await res.

How do I use HttpClient in xamarin forms?

The Xamarin. Android HttpClient configuration is in Project Options > Android Options, then click the Advanced Options button. The Xamarin. Android HttpClient configuration is in Project Options > Build > Android Build settings and click on the General tab.


2 Answers

I use HttpClient. A simple example:

var client = new HttpClient();
client.BaseAddress = new Uri("localhost:8080");

string jsonData = @"{""username"" : ""myusername"", ""password"" : ""mypassword""}"

var content = new StringContent (jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("/foo/login", content);

// this result string should be something like: "{"token":"rgh2ghgdsfds"}"
var result = await response.Content.ReadAsStringAsync();

Where "/foo/login" will need to point to your HTTP resource. For example, if you have an AccountController with a Login method, then instead of "/foo/login" you would use something like "/Account/Login".

In general though, to handle the serializing and deserializing, I recommend using a tool like Json.Net.

As for the question about how it works, there is a lot going on here. If you have questions about how the async/await stuff works then I suggest you read Asynchronous Programming with Async and Await on MSDN

like image 90
Jacob Shanley Avatar answered Oct 12 '22 03:10

Jacob Shanley


This should be fairly easy with HttpClient.

Something like this could work. However, you might need to proxy data from the device/simulator somehow to reach your server.

var client = new HttpClient();
var content = new StringContent(
    JsonConvert.SerializeObject(new { username = "myusername", password = "mypass" }));
var result = await client.PostAsync("localhost:8080", content).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
    var tokenJson = await result.Content.ReadAsStringAsync();
}

This code would probably go into a method with the following signature:

private async Task<string> Login(string username, string password)
{
    // code
}

Watch out using void instead of Task as return type. If you do that and any exception is thrown inside of the method that exception will not bubble out and it will go unhandled; that will cause the app to blow up. Best practice is only to use void when we are inside an event or similar. In those cases make sure to handle all possible exceptions properly.

Also the example above uses HttpClient from System.Net.HttpClient. Some PCL profiles does not include that. In those cases you need to add Microsoft's HttpClient library from Nuget. I also use JSON.Net (Newtonsoft.Json) to serialize the object with username and password.

I would also note that sending username and password in cleartext like this is not really recommended and should be done otherwise.

EDIT: If you are using .NET Standard on most of the versions you won't need to install System.Net.HttpClient from NuGet anymore, since it already comes with it.

like image 40
Cheesebaron Avatar answered Oct 12 '22 03:10

Cheesebaron