gpt4 book ai didi

c# - 使用 post 将 C# 数组发送到 PHP Web 服务

转载 作者:可可西里 更新时间:2023-11-01 13:24:27 26 4
gpt4 key购买 nike

我正在尝试使用下面的代码将此数组 string[] str = { "abc", "sdfsdf"}; 值发送到 PHP(网络服务),但它总是给我以下输出

enter image description here

在 PHP 文件中,我有以下代码实际接收数组并输出带有值的总结构:

<?php    
$messages = $_POST['messages'];
print_r($messages);
?>

问题可能是 PHP 无法读取我发送的数组;可能是因为我是从 C# 发送的。

能否请您告诉我如何正确发送数组,以便 PHP 网络服务可以读取它。

仅供引用:我无权编辑 Web 服务端的任何代码。

我的完整 C# 代码

string[] str = { "num" ,  "Hello World" };

string url = "http://localhost/a/cash.php";

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create( url );

ASCIIEncoding encoding = new ASCIIEncoding();

string postData ;//= "keyword=moneky";
postData = "&messages[]=" + str;

byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

MessageBox.Show(responseString);

最佳答案

经过反复试验,我终于找到了正确的解决方案。如果有人需要,这里是代码:

我不得不使用字典:

Dictionary<string, string> myarray =
new Dictionary<string, string>();

myarray .Add("0", "Number1");
myarray .Add("1", "Hello World");

然后

string str = string.Join(Environment.NewLine, myarray); 

然后我剩下的代码:

string url = "http://localhost/a/cash.php";

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create( url );

ASCIIEncoding encoding = new ASCIIEncoding();

string postData = "keyword=moneky";
postData += "&messages[]=" + str;

byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

MessageBox.Show(responseString);

关于c# - 使用 post 将 C# 数组发送到 PHP Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19208948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com