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 + "&";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With