从C#向PHP发布数据

本文关键字:数据 布数据 PHP | 更新日期: 2023-09-27 18:00:33

HI我一直在尝试从我的C#代码向PHP Web服务(第三方)发布数据。PHP Web服务说它需要一个参数c(缺少参数c是我得到的错误)。我使用JSON来发送数据,但我不明白如何给出参数。如果有人能阐明这一点,那就太好了。以下是我的代码:

DropYa d = new DropYa();
List<DropYaUser> d1 = new List<DropYaUser>();
DropYaUser ds = new DropYaUser();
ds.action = "create";
ds.groupid = 10;
ds.name = "Test";
ds.manager_key = "test";
d1.Add(ds);
WebRequest request = WebRequest.Create(" http://dev.dropya.net/api/Group.php");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
JavaScriptSerializer ser = new JavaScriptSerializer();//typeof(DropYaUser));
string postData = ser.Serialize(ds);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Console.Write("Wrote");
Console.Read();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Console.Read();
dataStream = response.GetResponseStream();
Console.Read();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
Console.Read();
response.Close();

从C#向PHP发布数据

任何post请求都将作为数据流读取。已发布表单的字段名称和值将以类似"c=ABC&d=123"的形式出现在流中,其中"c"answers"d"是表单字段。当然,您可以在没有任何表单字段名称的情况下发布,但在这种情况下,它需要"c"。你想做的是在你发布的数据前加上"c="。也许可以这样修改你的GetBytes行:

byte[] byteArray = Encoding.UTF8.GetBytes("c=" + postData);