简体   繁体   中英

Send C# array to PHP web service using post

I am trying to send this array string[] str = { "abc" , "sdfsdf" }; value to PHP (web service) using the code below but it is always giving me the following output

在此输入图像描述

In the PHP file I have the following code which actually receives the array and output the total structure with values:

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

Probably the problem is PHP is unable to read the array I am sending; may be because I am sending it from C#.

Could you please tell me how to send the array properly so that the PHP web service can read this.

FYI: I don't have the authority to edit any code in the web service end.

My Full C# Code

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

I have finally found the right solution myself after lots of trial and error. Here's the code in case if somebody needs:

I had to use dictionary:

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

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

And then

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

Then my rest of the codes :

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

Edit your C# code:

Old code

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

New code

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

While the op's answer works, I found the resulting string not so well formed (I really didn't like that Environment.NewLine ), so for anyone out there still trying to figure out this, the following piece of code will do the trick for any amount of postData parameters, even if some of those parameters are arrays or lists, :

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

The rest of the http call should work fine with the op's code. Below is the code for the IsCollection and IsDate methods:

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;
}

In my case this code will run in a SQL CLR C# Function, this is why I used only libraries available supported by SQL, thus my use of Uri.EscapeDataString instead of the more common HttpUtility.UrlEncode), but it works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM