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

时间:2013-10-06 12:39:02

标签: c# php arrays

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

enter image description here

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

编辑您的C#代码:

旧代码

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

新代码

string postData = "";
foreach (string oneString in str) {
   postData += "messages[]=" + oneString + "&";
}

答案 2 :(得分:0)

虽然op的答案有效,但我发现生成的字符串形式不太好(我真的不喜欢那个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),但它只能工作细