【问题标题】:How to send POST request containing array of object to PHP server from c# windows application?如何从 c# windows 应用程序向 PHP 服务器发送包含对象数组的 POST 请求?
【发布时间】:2019-05-31 00:43:17
【问题描述】:

我正在开发一个读取本地 MySQL 数据库的 C# 应用程序,并将数据作为 POST 请求发送到在线 PHP 服务器。

PHP 服务器已准备好接收这样的数据。 (来自 Postman x-www-form-url-encoded)

token:da979d2922c74d7851e6f0eff2270d73
branch:JKT
items[0][code]:0001-W*XL*B
items[0][name]:018/17 DRS XL BLUE
items[0][stock]:0
items[1][code]:0001-W*XL*BK
items[1][name]:018/17 DRS XL BLACK
items[1][stock]:0

这是我的 C# 代码。我无法将对象数组添加到字典中,所以我正在寻找其他方法。

string query = "SELECT * FROM items";
db.Connection.Open();

MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, db.Connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);

db.Connection.Close();

var dictionary = new Dictionary<string, string>();

dictionary.Add("token", "da979d2922c74d7851e6f0eff2270d73");
dictionary.Add("branch", "JKT");
dictionary.Add("items", dataTable); // Argument 2: cannot convert from 'System.Data.DataTable' to 'string'

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://mysite.test/sync")
{
    Content = new FormUrlEncodedContent(dictionary)
};
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();

除了 Dictionary 之外,还有其他方式可以发送 POST 请求表单数据吗?

【问题讨论】:

  • 这个答案有帮助吗stackoverflow.com/questions/3942427/…
  • @RiggsFolly 我认为这个答案与我的问题无关,我需要发布对象数组,同时那里的 OP 使用字符串数组。

标签: c# mysql http-post


【解决方案1】:

我的答案可能不是您想要的,但如果您传递字符串,您可以在 c# 中将它们与 ; 连接起来分隔符并爆炸字符串;在 php 上并获取数组。也可以试试:dictionary.Add("items[]", dataTable);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多