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

查看:66
本文介绍了在 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数据,然后从响应中解析token?我见过这样做的同步方法,但由于某种原因,它们不起作用(或者仅仅是因为我不知道它在哪个命名空间中).如果您采用异步方式来执行此操作,能否请您向我解释一下它是如何工作的?

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?

提前致谢.

推荐答案

我使用 HttpClient.一个简单的例子:

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 资源.例如,如果您有一个带有 Login 方法的 AccountController,那么您将使用类似 "/foo/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.

至于它如何工作的问题,这里有很多事情要做.如果您对 async/await 的工作原理有疑问,那么我建议您阅读 Asynchronous Programming在 MSDN 上使用异步和等待

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天全站免登陆