error when send special character from c# to webservice - c#

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.

Related

c# How to send HTTP command as this - http://192.168.10.1/api/control?alert=101002

I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!

Send a string from C# app to PHP

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

posting json data from c# windows application to php page

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.

Getting error while fetching information from windows live server

I am trying to authenticate user through windows live account with following code.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
WebRequest request = WebRequest.Create("https://oauth.live.com/token");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
request.Method = "POST";
Stream resp = request.GetRequestStream();
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
var response = request.GetResponse();
But I am getting following error at last line.
The remote server returned an error: (400) Bad Request.
what should I do for this?
Your issue is probably because we do not send bytes on "application/x-www-form-urlencoded" post but a string. Also the GetRespose is not looks like the correct one. Your code must be something like:
// I do not know how you create the byteArray
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// but you need to send a string
string strRequest = Encoding.ASCII.GetString(byteArray);
WebRequest request = WebRequest.Create("https://oauth.live.com/token");
request.ContentType = "application/x-www-form-urlencoded";
// not the byte length, but the string
//request.ContentLength = byteArray.Length;
request.ContentLength = strRequest.Length;
request.Method = "POST";
using (StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
}
string strResponse;
// get the response
using (StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
{
strResponse = stIn.ReadToEnd();
stIn.Close();
}
// and here is the results
FullReturnLine = HttpContext.Current.Server.UrlDecode(strResponse);

HttpWebRequest pass parameters to WebService

I have a webpage that need to pass data to web Service (SMS) and I tried to use WebRequest to do this work but when I use this class the following error appears:
Cannot close stream until all bytes are written
in the line after this line :
stOut.WriteLine(strNewValue,number,text);
What is the problem? I tried to use Flush() but didn't work either
public class SendSms
{
public SendSms(string number, string text)
{
string strNewValue;
string strResponse;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.buymessage.com/ostazSms/send.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
strNewValue = "usr=****&pwd=*****&to={0}&msg={1}";
req.ContentLength = strNewValue.Length;
using(StreamWriter stOut = new StreamWriter (req.GetRequestStream(), System.Text.Encoding.Unicode))
{
stOut.WriteLine(strNewValue,number,text);
}
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
}
}
Your issue is that you call WriteLine, which probably doesn't send all the data.
Here is a snippet that encodes the post data and sends it all:
string strNewValue = string.Format("usr=****&pwd=*****&to={0}&msg={1}", "A", "B");
byte[] byteArray = Encoding.UTF8.GetBytes (strNewValue);
req.ContentLength = byteArray.Length;
using (Stream dataStream = req.GetRequestStream ()) {
dataStream.Write (byteArray, 0, byteArray.Length);
}

Categories

Resources