We have webpage in our project where website post the XML data to.
string data = string.Concat("XMLParameter=", SampleXML, "&", "AccessCode=", "XYZ");
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream()); string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
When we pass following XML with post,
<notification timestamp="2009-09-11T11:51:07+02:00">
<reservation creation_date="2010-09-10T12:03:13">
</reservation>
</notification>
On the receiving end in our web page, timestamp we receive do not contain +. Instead of +, it gives us Space charactor. So, while deserializing it, we got error.
We get the data in page using Request.Form["XMLParameter"]
Any solution ???
You have a funny service where the XML data is posted as if it were coming from an HTML form with a text field containing the XML data.
As a consequence, the web server expects your data to be URL encoded. You even tell in the content type that it's encoded. But it isn't. You don't encode it anywhere in your code.
So if you want to stick with your funny service, then you need to run your XML data through HttpUtility.UrlEncode first.
Related
Trying to send a web request with some body content. The important part is that I need some data in the body of the post request. My understanding of how to do this is to open a WebRequestStream, and then write the bytes to it, then to close it. This is supposed to be simple. Here is my code:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create("http://localhost:50203/api/Values");//
request.Method = "POST";
byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
Stream requestBodyStream = request.GetRequestStream();
requestBodyStream.Write(requestBody, 0, requestBody.Length);
requestBodyStream.Flush();
requestBodyStream.Close();
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
myString = reader.ReadToEnd();
But the RequestBodyStream.Write method is not sending anything in the body. I know this because I'm running the server side program at the other end.
I also tried to do this with a StreamWriter instead of using a byte stream, and I get the same result. No matter how I do it, there is no content in the body.
My understanding is that closing the stream is what sends the actual data. I also tried adding a Flush() method to the stream.
Why is this method not producing any body?
Add 'ContentType' and 'ContentLength' headers to the request instance:
request.ContentType = "application/json"; // Or whatever you want
request.ContentLength = requestBody.Length;
So, I know how to get form data out by using Request.Form["abc"] however how would I go by getting the body out?
I've used this snippet in the below link:
https://gist.github.com/leggetter/769688
But, I'm not sure what to pass in as the Response.
In PHP to do this: file_get_contents('php://input'); and it's as simple as that.
Notes: The content type of the POST is application/json and the body contains the json string.
Thanks in advance.
If I understood your question correctly, here's what you could do when posting to a resource for which you expect a JSON response:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://foo.com/bar/");
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
//store json in a variable for later use
string json = readStream.ReadToEnd();
//make sure to close
response.Close();
readStream.Close();
Of course, this approach is synchronous; but, depending on your requirements, this might be just fine.
Since your question didn't specify whether you need to know how to parse the JSON itself, so I've left out an example of JSON parsing.
You'll need code similar to this to read the raw request body into a string variable.
using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
string text = reader.ReadToEnd();
}
I am trying to load an HttpWebResponse into an XmlDocument and am getting the exception "Data at the root level is invalid. Line 1, position 1". If I output the response to the Console I get "system.net.connectstream". The credentials don't seem to be my problem because if I enter an incorrect password my exception changes to the 404 error. Here is my code...
string username = "username";
string password = "password";
string url = "https://myurl.com";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(username, password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
Console.WriteLine(response.GetResponseStream());
xmlDoc.Load(response.GetResponseStream());
Thanks!
Calling ToString on GetResponseStream() isn't going to do much for you - Stream.ToString isn't overridden.
I suggest you use something like this for debugging::
// Prefer casting over "as" unless you're going to check it...
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
// For diagnostics, let's assume UTF-8
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Then replace the middle section (with StreamReader) with the XmlDocument.Load call.
I suspect you'll see that it's basically invalid XML, but the above should show you what it really is.
EDIT: Your comment shows the data as:
{"messages":{"message":"1 Device(s) returned."},"devices":{"device":
{"#id":"00","uuid":"00000000","phonenumber":"000000",
"user name":"0000","name":"Guy,Somebody","platform":"platform","os":"III",
"version":"1.1.1"}},"appName":"someApp"}
That's JSON. It's not XML. Don't try to load it as XML. You have two options:
Change what you're requesting so that you get an XML response back, if the server supports it
Parse it as JSON (e.g. with Json.NET) instead of as XML.
I've been converting a bunch of files from Coldfusion to C#, and all has been going swimmingly until now. I'm pretty much learning ColdFusion as I go, and I barely ever write in C# so I'm stuck here. Can anybody help explain how I would go about translating this chunk of code into C#?
<cfobject type="COM" action="Create" name="objServerXMLHttp" class="msxml2.ServerXMLHTTP.3.0">
<cfset objServerXMLHttp.open("POST", "http://URL", True , "Me.User", "Me.Password")>
<cfset objServerXMLHttp.setRequestHeader("Content-Type", "text/xml")>
<cfset objServerXMLHttp.setRequestHeader("charset", "utf-8")>
<cfset objServerXMLHttp.send("#XMLRequest#")>
<cfset thread = CreateObject("java", "java.lang.Thread")>
For some background, I'm basically just taking info from a database, surrounding it with XML tags in a string, creating an XML file out of the string, and now here I am.
The direct translation is easy in C# 4.0 (VS2010) with the dynamic keyword:
dynamic objServerXMLHttp = Activator.CreateInstance(Type.GetTypeFromProgID("msxml2.ServerXMLHTTP.3.0"));
objServerXMLHttp.open("POST", "http://chrdevweb:8080/mellibase/webservice/rest", true, "Me.User", "Me.Password");
objServerXMLHttp.setRequestHeader("Content-Type", "text/xml");
objServerXMLHttp.setRequestHeader("charset", "utf-8");
objServerXMLHttp.send("#XMLRequest#");
So just to break it down as to what this coldfusion code is doing (which you probably know anyway):
It is instantiating an object type msxml2.ServerXMLHTTP in memory.
It is then using that object to construct an XML document.
It is then sending that (via HTTP POST) to the URL: http://chrdevweb:8080/mellibase/webservice/rest
And lastly, it seems to instantiate a java object (not sure its related).
So in asp.net using c#, the post code would like so:
HttpWebRequest request=null;
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
string result=string.Empty;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
The result variable in the end would hold your response. The 'url' is the url you are posting to, and 'postData' is your xml string.
To construct the XML doc, you can use XMLdocument in c#, or you can just put a string together.
PS: this is untested, so there may be a syntax error somewhere :)
I'm developing the client-side of a third party webservice. The purpose is that I send xml-file to the server.
How should I attach the xml-file to the httpwebrequest? What contentType is needed? More suggestions?
I cannot use mtom or dime.ie because I am using httpwebrequest. I am unable to use WCF either.
Here is a very basic method of sending XML structured data using HttpWebRequest (by the way you need to use request.ContentType = "application/xml";) :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(myUrl));
request.Method = "POST";
request.ContentType = "application/xml";
request.Accept = "application/xml";
XElement redmineRequestXML =
new XElement("issue",
new XElement("project_id", 17)
);
byte[] bytes = Encoding.UTF8.GetBytes(redmineRequestXML.ToString());
request.ContentLength = bytes.Length;
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
// Log the response from Redmine RESTful service
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Logger.Info("Response from Redmine Issue Tracker: " + reader.ReadToEnd());
}
I use this at one of my projects (NBug) to submit an issue report to my Redmine issue tracker which accepts XML structured data over web requests (via POST). If you need further examples, you can get a couple of fully featured examples here: http://nbug.codeplex.com/SourceControl/list/changesets (click 'Browse' under 'Latest Verion' label on the right then navigate to "NBug\Submit\Tracker\Redmine.cs")