c# - 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();
?>
解决方案
推荐阅读
- reactjs - 您能否将脚本注入到 React 页面(使用 Draft.js 编辑器)以将 HTML 附加到编辑器的现有内容?
- azure-cosmosdb - 嵌套对象子级的 Cosmos DB SQL API 查询
- android - 工具栏隐藏其他元素 android kotlin
- xaml - 按钮在较低分辨率下转义堆栈布局
- php - 如何从 PHP post 在 virtualenv 中运行 python 脚本
- javascript - Vue.js 不会在屏幕上显示多个组件
- azure - 连接到 Dynamics 365 for Operations 的试用实例
- python - PyTorch LSTM 状态
- oracle - Oracle 中包声明 DDL 中依赖类型声明的 Flyway 错误
- laravel - 如何在 Laravel 中添加动态结果部分