C# HttpWebRequest with XML Structured Data - c#

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

Related

Send binary data with HttpWebRequest

I want to send some binary data from my WinForms c# application.
The server expects the data will be sent using POST request. I need to send several files and parameters, something like this:
file1=<binary data>
file2=<binary data>
desc1=<string>
desc2=<string>
I've searched that in Internet and MSDN and the code bellow is the most popular:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://example.com");
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data";
webRequest.ContentLength = data.Length;
using (Stream postStream = webRequest.GetRequestStream())
{
postStream.Write(data, 0, data.Length);
postStream.Close();
}
But I don't understand how to use this code to send several parameters? How can I set name for each of them?
Using GET I whould do &file=...&file2=...&desc1=...&desc2=... but using POST I have no clue what to do.

cannot call web api successfully when sending xml data

I cannot successfully call an API using C# at the moment. I have attached a screen shot of the call being successfully made with Chrome PostMan although I'm not able to replicate it in C#. He is my attempt so far which fails. The response I get back from the server is included below. Can anyone see what I'm doing wrong?
Many thanks,
James
Code Snippet
const string xml = "<Envelope><Body> <AddRecipient>...";
var req = (HttpWebRequest)WebRequest.Create(ApiUrl);
var requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
req.Method = "POST";
req.Headers.Add("Authorization", "Bearer " + token);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestBytes.Length;
var requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
var res = (HttpWebResponse)req.GetResponse(); // Call API
var sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
var backstr = sr.ReadToEnd();
sr.Close();
res.Close();
Chrome PostMan
Response back from API
<Envelope><Body><RESULT><SUCCESS>false</SUCCESS></RESULT><Fault><Request/><FaultCode/><FaultString>Server Error</FaultString><detail><error><errorid>50</errorid><module/><class>SP.API</class><method/></error></detail></Fault></Body></Envelope>
Is there any documentation about what error 50 is? Could just be a bad pram? If not I recommend downloading fiddler. You can then properly compare the request from both PostMan and your application to see what the actual difference is.

Web API and WPF client

I've followed the following article to set up a simple Web API solution:
http://www.codeproject.com/Articles/350488/A-simple-POC-using-ASP-NET-Web-API-Entity-Framewor
I've omitted the Common project, Log4Net and Castle Windsor to keep the project as simple as possible.
Then I created a WPF project. However, now which project should I reference in order access the WebAPI and the underlying models?
Use the HttpWebRequest class to make request to the Web API. Below a quick sample for something I've used to make requests to some other restful service (that service only allowed POST/GET, and not DELETE/PUT).
HttpWebRequest request = WebRequest.Create(actionUrl) as HttpWebRequest;
request.ContentType = "application/json";
if (postData.Length > 0)
{
request.Method = "POST"; // we have some post data, act as post request.
// write post data to request stream, and dispose streamwriter afterwards.
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
writer.Close();
}
}
else
{
request.Method = "GET"; // no post data, act as get request.
request.ContentLength = 0;
}
string responseData = string.Empty;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseData = reader.ReadToEnd();
reader.Close();
}
response.Close();
}
return responseData;
There are also a nuget package available called "Microsoft ASP.NET Web API client libraries" which can be used to make requests to the WebAPI. More on that package here(http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client)

How we can Upload files into rackspace cloud container with API in C#

I want to Upload files into rackspace cloud container with API in C# and I am using .net 4.0 version. So, how I can create webrequest for this. Even I successfully created containers with the same request but I am not able to create object into my container.
Number of times I tried to upload my file into my container but I am continuously getting error like Unauthorized access and my code is shown below:
HttpWebRequest request = WebRequest.Create(new Uri(authInfo.StorageUrl + "/TestContainer/myfile.txt")) as HttpWebRequest;
request.Method = "PUT";
request.Headers["X-Auth-Token"] = MyToken;
byte[] data = System.IO.File.ReadAllBytes(#"D:\myfile.txt");
request.ContentLength = data.Length;
//request.Headers["Content-Length"] = "512000";
var response = request.GetResponse();
Please tell me what I am doing wrong with this.
You haven't written the bytes to the request stream. Do something like this:
Stream reqStream = request.GetRequestStream();
reqStream.Write(fileBytes, 0, fileBytes.Length);
reqStream.Close();
Webresponse response = request.getresponse();

Programmatically call webmethods in C#

I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser.
This is the code which calls the webmethod programmatically:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Console.WriteLine(r.ReadToEnd());
Following on from the comments above. If you have a WSDL file that describes your service you use this as the information required to communicate with your web service.
Using a proxy class to communicate with your service proxy is an easy way to abstract yourself from the underlying plumbing of HTTP and XML.
There are ways of doing this at run-time - essentially generating the code that Visual Studio generates when you add a web service reference to your project.
I've used a solution that was based on: this newsgroup question, but there are also other examples out there.
FYI, your code is missing using blocks. It should be more like this:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream reqstm = req.GetRequestStream())
{
doc.Save(reqstm);
}
using (WebResponse resp = req.GetResponse())
{
using (Stream respstm = resp.GetResponseStream())
{
using (StreamReader r = new StreamReader(respstm))
{
Console.WriteLine(r.ReadToEnd());
}
}
}

Categories