使用Xamarin Forms C#发送HTTP Post请求 [英] Send HTTP Post request in Xamarin Forms C#

查看:918
本文介绍了使用Xamarin Forms C#发送HTTP Post请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开始之前,我想说我已经用谷歌搜索了这个问题的解决方案,但是要么不理解它们(我是新手),要么不起作用.

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.

我想要做的就是以以下格式将JSON数据发送到localhost:8000上的REST API:

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

如何发送json数据,然后从响应中解析令牌? 我已经看到了执行此操作的同步方法,但是由于某些原因,它们不起作用(或者仅仅是因为我不知道它在哪个命名空间中).如果您采用异步方式执行此操作,能否请您向我解释其工作原理?

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?

谢谢.

推荐答案

我使用

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

"/foo/login"需要指向您的HTTP资源的位置.例如,如果您的AccountController具有Login方法,则可以使用"/Account/Login"之类的东西代替"/foo/login".

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".

不过,通常来说,要处理序列化和反序列化,我建议使用类似 Json.Net 的工具

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

关于它如何工作的问题,这里有很多事情发生.如果您对异步/等待的东西的工作方式有疑问,那么我建议您阅读异步编程在MSDN上使用Async和Await

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

这篇关于使用Xamarin Forms C#发送HTTP Post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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