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 :)
Related
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
This is the code which I have written on the app side, which is being developed using Xamarin
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(ApiUrl);
objRequest.Method = "POST";
objRequest.ContentType = "application/x-www-form-urlencoded";//"application/json;charset=utf-8";
objRequest.Headers.Add("Authentication", "web60134");
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] arrRequest;
arrRequest = utf8Encoding.GetBytes(JsonReq);
objRequest.ContentLength = arrRequest.Length;
Stream requestStream = objRequest.GetRequestStream();
requestStream.Write(arrRequest, 0, arrRequest.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)objRequest.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
string result = streamReader.ReadToEnd();
This is the code written on the server side which is PHP
$recvd = $_POST['TH_ET_LoginProcess'];
$recvdArr = json_decode($recvd);
I tried using file_get_contents("php://input") but both the methods are returning null or nothing.
What is the best way to read JSON at web server using PHP in such scenario?
Best is a quite subjective term.
However what I am successfully using RestSharp in an Xamarin Android solution.
I also highly recommend PostMan and Fiddler for troubleshooting your service.
Regarding your code:
You should be disposing those objects that are disposable, preferable with the 'using' statement. This includes HttpWebResponse object is as well as the Stream ones.
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'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")
Im stuck on this httpWebRequest problem. I need to send XML to a website. But I keep getting negative responses on my request. I saw some code examples where the ContentLength was set... And that might be the issue but I don't know....
The XML written in writePaymentRequest(...) is exactly as the website needs it to be, because they got my xml markup and they succeeded, in another programming language though. The result only contains their error instead of the information I'm supposed to be receiving.
I can't set the contentlength because I don't know the length when I create the writer with the requeststream in it.
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://some.website.com");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
using (writer = new XmlTextWriter(httpWebRequest.GetRequestStream(), System.Text.Encoding.UTF8))
{
writePaymentRequest(writer, registrant, amount, signature, ipaddress);
}
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
String stringResult = streamReader.ReadToEnd();
streamReader.Close();
You would know the length if you wrote the XmlTextWriter to something like a MemoryStream first. From there, you could get the bytes, set the httpWebRequest.ContentLength to the length of the byte array, and then write the byte array to your request
edit
The middle of your code would look something like this (I think):
MemoryStream ms = new MemoryStream();
using (writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8))
{
writePaymentRequest(writer, registrant, amount, signature, ipaddress);
}
byte[] bytes = ms.ToArray();
ms.Close();
httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
httpWebRequest.ContentLength = bytes.Length;
edit #2
Instead of XmlTextWriter(ms, System.Text.Encoding.UTF8), try XmlTextWriter(ms, new UTF8Encoding(false)) to see if that fixes the encoding issue