How do I post a json string from c# windows application to a php page?
I am using the following code but it returns null string from php page?
string Uname, pwd, postData, postData1;
Uname = txtUname.EditValue.ToString();
pwd = txtPassword.EditValue.ToString();
List<request1> JSlist = new List<request1>();
request1 obj = new request1();
obj.emailid = Uname;
obj.password = pwd;
JSlist.Add(obj);
JavaScriptSerializer serializer = new JavaScriptSerializer();
string s;
s = serializer.Serialize(obj);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://lab.amusedcloud.com/test/login_action.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(s);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
MessageBox.Show(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
MessageBox.Show(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
PHP
<?php
$json_array = json_decode($_POST['json']);
?>
connection established successfully but this php page returns array(0){}
Based on the ContentType property, it looks like you should be form encoding the content your sending to the PHP script. If thats the case you need to make sure the content you are sending is in key/value format:
[key]=[value]
In your case it looks like the PHP script is expecting a parameter with the key "json", so the data your sending would be something like:
"json=" & s
Hope that helps.
Related
I am trying to get cognos report using siteminder token, below is my code.
string cognosUrl = "https://cognos.blah.com";
string reportPath = "/c10/cgi-bin/cognosisapi.dll/rds/reportData/report/"; string reportId = "ildjfsldkf"; //prod
cognosUrl += string.Concat(reportPath, reportId,"?blahblah");
string targetUrl = cognosUrl;
string strFormvalues = string.Concat("TARGET=",targetUrl);
ASCIIEncoding encoder = new ASCIIEncoding();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
byte[] data = encoder.GetBytes(strFormvalues);
request.AllowAutoRedirect = false;
request.Timeout = 120000;
request.ContentLength = data.Length;
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Method = "POST";
request.Headers.Add(HttpRequestHeader.Cookie,"SMSESSION="+stoken);
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(json);
MemoryStream restream = new MemoryStream(byteArray);
using (Stream output = File.OpenWrite(#"c:\\Projects\\Test_"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+".txt"))
using (Stream input = restream)
{
if (input != null) input.CopyTo(output);
}
// var results = serializer.DeserializeObject(json);
reader.Close();
dataStream.Close();
response.Close();
But I am getting response as " DPR-ERR-2101 Your request was invalid.Please contact your administrator."
I am not using C# myself, but a few recommendations while debugging this:
If you are only posting a URL, why not use GET instead of POST?
Try paste the targetURL in your browser, see what happens.
In my setup, when I paste the URL in the browser, I am always redirected before I receive an answer. (to a URL like, /cgi-bin/cognosisapi.dll/rds/sessionOutput/conversationID/i292ED29A62474697AD44306A388F5BBB You are preventing that to happen, that might be an issue)
Hope that helps.
I have a webpage :http://180.92.171.80/ffs/data-flow-list-based/. After Filling Basin Name and River Name from Drop-down Menu, Station Names are appeared in Flood Forecasting Sites, when I select any of them, it automatically redirect to return that station's information. I need to save that information(Name, Date and present Water Level) on regular basis obviously with C#.
I have some knowledge in C#. I have tried some codes on Webpage posting and Name Value Collection but yet not successful.
Codes are:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com");
request.Method = "POST";
formContent = "FormValue1=" + someValue +
"&FormValue2=" + someValue2 +
"&FormValue=" + someValue2;
byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = HttpUtility.UrlDecode(reader.ReadToEnd());
//You may need HttpUtility.HtmlDecode depending on the response
reader.Close();
dataStream.Close();
response.Close();
Another Code:
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
Can anyone help me in this regard?? It will be a great help for me.
Thanks in advance.
You can also read data through Jquery by their div or span value
I want to send string from my C# app to my PHP page and I tried some different solutions that i found in the internet. One of them is this:
C# code:
string url = "http://localhost:8080/test.php";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message=" + str;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
and PHP code:
foreach($_POST as $pdata)
echo $pdata;
But it's just a blank page. I dont know what the problem is.
I haven't used c# in a long time, but this should be the solution:
string url = "http://localhost:8080/test.php";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message=" + str;
UTF8Encoding utf8 = new UTF8Encoding();
byte[] postBytes = utf8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(resStream);
string responseText = sr.ReadToEnd();
What I did was change the encoding from ASCII to UTF8. UTF8 is what application/x-www-form-urlencoded expects.
As for your php, I assume you have opening and closing brackets on your foreach method.
Edit:
Okay, well I noticed an error in your c#. You were getting the response stream twice. That might have caused some error, but here is how I would structure my php:
<?php
foreach($_POST as $key => $value){
echo $value . "<br>";
}
?>
Can you kindly educate me in how can I see the string that I have created, written in the web server location, using c#.
The output I see in the file, that I write in the server location has only the "Date", "Time" and after 4 commas "my IP address"
somthing like this: 2013/11/12,00:20:56,,,,,x.x.x.x,
I would like to see my created string written in the places where we see the commas.
Here is my code:
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(""www.xyz.com/.../....MyUrlLocation");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = Environment.UserName + "," + sw.Elapsed.ToString() + "," + NumberOFProperties.ToString();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(postData);
//byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "PUT";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
bool bIfCanWrite = dataStream.CanWrite;
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
string strLine = reader.ReadLine();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
im using method POST to send string to REST service.
//--------------------------Method Post--------------------------
public static string methodPost(string header,string url,string body)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
if(header!=null) request.Headers.Add(header);
request.ContentType = "application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(body);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var response = request.GetResponse();
Stream stream2 = response.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
String ok = reader2.ReadToEnd();
return ok;
}
if string body ="test send string" : success, but string body ="test send ' string" : not success.
how to fix it? thank!
"test send ' string" is legal json, but you might try "test send \' string". If that doesn't work, you'll need to ask the people who manage the web service.