首页 > 解决方案 > C# WebClient - 非常简单的将 json 发布到 PHP 服务器

问题描述

我的服务器使用 PHP 并使用$_POST变量。我的客户使用 C#。

有了ContentType = application/json,我需要$post = json_decode(file_get_contents('php://input'), true);在 PHP 服务器中使用

但是变量是一个带有json字符串的数组,ContentType = application/x-www-form-urlencoded例如$_POST[ **the json variable as string** ]

使用时我的代码有什么问题application/x-www-form-urlencoded


示例:

var post = new Dictionary<string, object>
{
    ["key1"] = "data1",
    ["key2"] = new List<string>{ "data2", "data3" }
};

获取[ "[\"key1\"] = \"data1\" ... \"data3\"]" ]$_POST(1个数组,1个字符串)


C# 客户端:

var post = new Dictionary<string, object>
{
    ["key1"] = "data1",
    ["key2"] = new List<string>{ "data2", "data3" }
};
var url = "https://urlrandom.com";
var method = "POST";

using (var webClient = new WebClient())
{
    webClient.Headers[HttpRequestHeader.UserAgent] = "Other";
    webClient.Headers[HttpRequestHeader.Accept] = "application/json";
    webClient.Headers[HttpRequestHeader.ContentType] = ; // "application/json" or "application/x-www-form-urlencoded"

    var dataString = JsonConvert.SerializeObject(post);
    var bytes = Encoding.UTF8.GetBytes(dataString);
    var jsonBytes = webClient.UploadData(url, method, bytes);
    var jsonString = Encoding.UTF8.GetString(jsonBytes);
    var json = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

    return json;
}

PHP服务器:

<?php 
echo array_key_exists($_POST, "key1"); /* false with application/x-www-form-urlencoded */
exit();
?>

标签: c#phppostwebclient

解决方案


推荐阅读