6

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

在此处输入图像描述

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

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

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

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

仅供参考:我无权在 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);
4

3 回答 3

3

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

我不得不使用字典:

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);
于 2013-10-06T15:12:04.623 回答
1

编辑您的 C# 代码:

旧代码

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

新代码

string postData = "";
foreach (string oneString in str) {
   postData += "messages[]=" + oneString + "&";
}
于 2013-10-06T14:39:05.180 回答
0

虽然操作的答案有效,但我发现生成的字符串格式不太好(我真的不喜欢那个Environment.NewLine),所以对于仍然试图弄清楚这一点的任何人来说,下面的代码可以解决任何数量的问题postData 参数,即使其中一些参数是数组或列表,:

string[] str = { "abc" ,  "sdfsdf" }
var postData = new Dictionary<string, object>()
{
    { "keyword", "monkey" },
    { "messages", str}
};

// Serialize the postData dictionary into a string
string serializedPostData = string.Empty;
foreach (KeyValuePair<string, object> pair in postData)
{
    if (IsCollection(pair.Value))
    {
        foreach (object item in (IEnumerable)pair.Value)
        {
            //%5B%5D is encoding for []
            serializedPostData += Uri.EscapeDataString(pair.Key) + "%5B%5D=" + Uri.EscapeDataString(Convert.ToString(item)) + "&";
        }
    }
    else if (IsDate(pair.Value))
    {
        serializedPostData += Uri.EscapeDataString(pair.Key) + "=" +
                                Uri.EscapeDataString(((DateTime)pair.Value).ToString("o")) + "&";
    }
    else
    {
        serializedPostData += Uri.EscapeDataString(pair.Key) + "=" +
                                Uri.EscapeDataString(Convert.ToString(pair.Value)) + "&";
    }
}
serializedPostData = serializedPostData.TrimEnd('&');
byte[] data = Encoding.ASCII.GetBytes(serializedPostData);

其余的 http 调用应该可以与 op 的代码一起正常工作。下面是 IsCollection 和 IsDate 方法的代码:

private static bool IsCollection(object obj)
{
    bool isCollection = false;

    Type objType = obj.GetType();
    if (!typeof(string).IsAssignableFrom(objType) && typeof(IEnumerable).IsAssignableFrom(objType))
    {
        isCollection = true;
    }

    return isCollection;
}

private static bool IsDate(object obj)
{
    bool isDate = false;

    if (typeof(DateTime) == obj.GetType() || typeof(DateTimeOffset) == obj.GetType())
    {
        isDate = true;
    }

    return isDate;
}

在我的情况下,此代码将在 SQL CLR C# 函数中运行,这就是为什么我只使用 SQL 支持的库,因此我使用 Uri.EscapeDataString 而不是更常见的 HttpUtility.UrlEncode),但它工作得很好。

于 2018-05-19T18:23:39.033 回答