gpt4 book ai didi

c# - 如何使用 WinRT 将 json 发布到网站?

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:22 24 4
gpt4 key购买 nike

我正在尝试将此 JSON 数据字符串发布到我的 php 站点:

{
"tag":"login"
"email":"email@email.com"
"password":"P@ssw0rd"
}

这是我的 C# 代码:

        HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/login/");
string link = "http://localhost/login/";

UserCredentials cred = new UserCredentials(email.Text, pass.Password.ToString());
var data = new Dictionary<string, List<UserCredentials>>();
string json = JsonConvert.SerializeObject(data, Formatting.Indented);


HttpResponseMessage re = await client.PostAsync(link, new StringContent(json));

用户凭证类:

public class UserCredentials
{
public UserCredentials(string user, string pass)
{
User = user;
Pass = pass;
Tag = "login";
}

internal string User;
internal string Pass;
internal string Tag;
}

在我的 php 脚本中:

<?php

if (isset($_POST['tag']) && $_POST['tag'] != '') {
echo "got tags";
else
echo "didn't get anything";
?>

有谁知道我应该如何通过 postasync 方法发送标签?我越来越“什么都没得到”..请帮忙

最佳答案

首先,修复您的 UserCredentials 类。让您的成员公开,而不是内部。

public class UserCredentials
{
public UserCredentials(string user, string pass)
{
User = user;
Pass = pass;
Tag = "login";
}

public string User;
public string Pass;
public string Tag;
}

其次,仅序列化您的凭据。

UserCredentials cred = new UserCredentials(email.Text, pass.Password.ToString());
string json = JsonConvert.SerializeObject(cred, Formatting.Indented);
System.Diagnostics.Debug.WriteLine(json);

您将在“输出”窗口中看到如下内容:

{
"User": "me@hotmail.com",
"Pass": "ILoveToEatGrapes",
"Tag": "login"
}

三、将StringContent替换为FormUrlEncodedContent

如果您使用的是 PHP $_POST,那么您必须在 HTTP 请求中发送类似 key1=value1&key2=value2 的内容。这称为 x-www-form-urlencoded,HttpClient 包含用于此的正确类:FormUrlEncodedContent

FormUrlEncodedContent 接收键/值对字典。

// Create the list of keys and values.
var data = new Dictionary<string, string>();
data["tag"] = json;

// Send my keys and values.
HttpClient client = new HttpClient();
string link = "http://localhost/login/";
HttpResponseMessage re = await client.PostAsync(link, new FormUrlEncodedContent(data));

这将通过连接发送:

POST /login/ HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost
Content-Length: 142
Expect: 100-continue
Connection: Keep-Alive

tag=%7B%0D%0A++%22User%22%3A+%22me%40hotmail.com%22%2C%0D%0A++%22Pass%22%3A+%22I
LoveToEatGrapes%22%2C%0D%0A++%22Tag%22%3A+%22login%22%0D%0A%7D

第四,在PHP中使用你的数据

正如你在上面看到的,数据是用很多百分号编码的。 PHP 会自动为您解码数据,因此您无需担心。

要将凭据从 json 转换为数组,您可以使用 json_decode

$cred = json_decode($_POST['tag']);

关于c# - 如何使用 WinRT 将 json 发布到网站?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com