Send C # array to PHP web service using message

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

enter image description here

In the PHP file, I have the following code that actually gets an array and displays a general structure with values:

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

Probably the problem is that PHP cannot read the array that I am sending; maybe because I am sending it with C #.

Could you tell me how to send the array correctly so that the PHP web service can read it.

FYI: I have no right to edit any code at the end of the web service.

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); 
+6
source share
2 answers

I finally found the right solution after a lot of trial and error. Here's the code in case someone needs:

I had to use a 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 other codes are:

 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
source

Change your code to C #:

Old code

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

New code

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

Source: https://habr.com/ru/post/955344/


All Articles