How to handle and get the body from POST using .NET C#? - c#

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();
}

Related

How to use streamReader(or similar) for a HttpWebResponse stream

I am currently trying to retrieve a xml response and parse the result from a web service, but I have ran into issues when receiving the response as a stream and using stream reader to read the result and convert the xml response to a string so it can be parsed to get a result later.
When testing I receive an error that there is illegal characters in path, as the stream reader only accepts a file path not the actual xml response object itself. After extensive searching most of the similar posts on here, most people point to either textreaders or xmlreaders but as the HttpWebResponse returns a stream I can't use those. Does anyone have a idea's or pointers to help me overcome this?
I have included a snippet of the code to how I am handling the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string soapResult = responseStream.ReadToEnd();
Here is the code for the request, just in case it helps.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Location);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "application/soap+xml; charset=UTF-8";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
Thanks

Invalid Data HttpWebResponse from HttpWebRequest C#

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":"000‌​000",
"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.

Translating COM objects (or possibly XMLHTTP) in Coldfusion to C#

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 :)

Deserialize problem for timestamp in ASP.NET

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.

How to POST Raw Data using C# HttpWebRequest

I am trying to make a POST request in which I am supposed to send Raw POST data.
Which property should I modify to achieve this.
Is it the HttpWebRequest.ContentType property. If, so what value should I assign to it.
public static string HttpPOST(string url, string querystring)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
try
{
requestWriter.Write(querystring);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
You want to set the ContentType property to the mime type of the data. If its a file, it depends on the type of file, if it's plain text then text/plain and if it's an arbitrary binary data of your own local purposes then application/octet-stream. In the case of text-based formats you'll want to include the charset along with the content type, e.g. "text/plain; charset=UTF-8".
You'll then want to call GetRequestStream() and write the data to the stream returned.

Categories