How to send POST request containing array of object to PHP server from c# windows application?

荒凉一梦 提交于 2019-12-13 03:42:34

问题


I'm developing a C# application that reads local MySQL database, and send the data as POST request to online PHP server.

The PHP server is ready to receive data like this. (It is from 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

This is my c# code. I can't add array of objects to dictionary, so I'm looking for other way around.

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();

Is there other way to send POST request form data aside from Dictionary?


回答1:


My answer may be not one that you want, but if u pass strings u can concatenate them in c# with ; separator and do explode string ; on php and get array. Also try: dictionary.Add("items[]", dataTable);



来源:https://stackoverflow.com/questions/56342631/how-to-send-post-request-containing-array-of-object-to-php-server-from-c-sharp-w

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!