Send a string from C# app to PHP - c#

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

Related

Send an HTTP POST request with C#

I'm try to Send Data Using the WebRequest with POST But my problem is No data has be streamed to the server.
string user = textBox1.Text;
string password = textBox2.Text;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username" + user + "&password" + password;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr99 = new StreamReader(stream);
MessageBox.Show(sr99.ReadToEnd());
sr99.Close();
stream.Close();
here the result
It's because you need to assign your posted parameters with the = equal sign:
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
See the username= and &password= in post data formatting.
You can test it on this fiddle.
Edit :
It seems that your PHP script has parameters named diffently than those used in your question.

HttpWebRequest webservice call returns Request format is invalid: text/xml;charset=UTF-8

Trying to call WebService using HTTPWebRequest and posting data, it results in invalid request format, I have added http verbs post in both client and webservice, any ideas here ?
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/WS/test.asmx/GetData");
String xmlString = "Montreal";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "text/xml;charset=UTF-8";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close(); //fails here with error message Request format is invalid: text/xml;charset=UTF-8.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
I got to modify the approach, this worked for me.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/WS/test.asmx");
String xmlData = "Montréal";
String xmlString = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/> <soapenv:Body><tem:GetData><tem:data>" + xmlData + "</tem:data></tem:GetData></soapenv:Body></soapenv:Envelope>";
byte[] bytesToWrite = Encoding.UTF8.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "text/xml;charset=UTF-8;";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
catch (Exception ex)
{
string msg = ex.Message;
}

Web Page Posting and Capturing Response using C#

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

Custom header not included in the http post request

Box.com's Enterprise User Provisioning API requires OAUTH2 token in the header of the request ("Authorization: Bearer faKE_toKEN_1234"). I've ran the code below against http://www.xhaus.com/headers, http://httpbin.org/post and http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi and observed packets with Microsoft Network Monitor and as far as I know my request header does not include the "Authorization" value I wish to include there.
Is the code below missing something (code or a point)?
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(API_URL);
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout=10000;
string postData = Parameters;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);
request.ContentLength = byte1.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
//This is puzzling me, why can't I see this header anywere
//when debugging with packet monitor etc?
request.Headers.Add("Authorization: Bearer " + access_token);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string txtResponse = reader.ReadToEnd ();
return txtResponse;
I think you need to set the header before you write the postData and close the request stream. This appeared to work for me:
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.xhaus.com/headers");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Add("Authorization: Bearer_faKE_toKEN_1234");
string postData = "postData";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string txtResponse = reader.ReadToEnd();
Console.WriteLine(txtResponse);
Console.ReadKey();
}

Consume wcf service using HttpWebRequest c#

HttpWebRequest req = null;
HttpWebResponse res = null;
const string url = http://localhost/MyService/EService.svc/CreateMethod";
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";
req.Headers.Add("App", "Application");
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes("{ itemlist: 'sasfs' }");
req.ContentLength = data.Length;
res = (HttpWebResponse)req.GetResponse();
Stream responseStream = res.GetResponseStream();
var streamReader = new StreamReader(responseStream);
string txt = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
responseStream.Close();
responseStream.Dispose();
I have to use above code to consume service, but i am getting different errors-
1) You must provide a request body if you set ContentLength>0 ....
What is the code I am missing exactly here.
You missing few lines of code. You only setting ContentLength but you do not write content.
req.ContentLength = data.Length;
//Write request data(setting content of request)
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
res = (HttpWebResponse)req.GetResponse();

Categories

Resources