14

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.

AGB
  • 2,230
  • 1
  • 14
  • 21
alexcons
  • 531
  • 3
  • 8
  • 18

3 Answers3

25

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

big_water
  • 3,024
  • 2
  • 26
  • 44
Jacob Shanley
  • 893
  • 1
  • 8
  • 19
  • Because it is an async function, as it uses await, what wound I change my function signature to? I currently have: private void authLogin(string user, string pass) – alexcons Apr 06 '16 at 19:45
  • 1
    Just add an async in the method signature: private async void authLogin(string user, string pass) – Jacob Shanley Apr 06 '16 at 19:49
  • 2
    Please dont make it void, if an exception throws it will go unhandled and the app blows up. – Cheesebaron Apr 06 '16 at 19:50
  • Ah, yeah I would at least return Task or Task, T being whatever type makes sense for your program here. Looks like [Cheesebaron updated his answer](http://stackoverflow.com/a/36459603/1118082) – Jacob Shanley Apr 06 '16 at 19:58
  • @JacobShanley You should only use `async void` for event handlers. In other cases make it `async Task` T being the return type, or `async Task` if the method shouldn't return anything. – Matheus Rocha Oct 24 '19 at 09:48
  • Yes, I am well aware of this. Thank you. – Jacob Shanley Oct 25 '19 at 10:53
11

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.

Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
-1

try this code.

HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(APIAddress); // Insert your API URL Address here.
            string serializedObject = JsonConvert.SerializeObject(data);
            HttpContent contentPost = new StringContent(serializedObject, Encoding.UTF8, "application/json");
            try
            {
                HttpResponseMessage response = await httpClient.PostAsync(ControllerWithMethod, contentPost);
                return response;
            }
            catch (TaskCanceledException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage();
            }
ammad khan
  • 1,022
  • 1
  • 10
  • 14