Requests are sent from you client application to a particular URI (Uniform Resource Identifier), such as a Web page on a server. The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application.
Here's the steps to send data to a server. This method is commonly used to post data to a Web page:
1. Create a WebRequest instance by calling Create with the URI of the resource that accepts data
string uri = "http://127.0.0.1/webmsgbroker/default.aspx";
WebRequest req = WebRequest.Create(uri);
2. Specify the protocol method and the content type to use in sending the request
req.Method = "POST";
req.ContentType = "text/xml";
3. Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the xml text into the stream, GetTextFromXMLFile is a custom function the convert XML to stream
writer.WriteLine(this.GetTextFromXMLFile("C:/test.xml"));
writer.Close();
4. Send the data to the webserver and wait for the response.
rsp = req.GetResponse();
Here is the complete sample sourcecode:
//Function to convert XML to stream
private string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
//Button to Post data to web page
private void button1_Click(object sender, EventArgs e)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
//URL of message broker
string uri = "http://127.0.0.1/webmsgbroker/default.aspx";
req = WebRequest.Create(uri);
req.Proxy = wproxy;
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the xml text into the stream
string fileName = "C:/test.xml";
writer.WriteLine(this.GetTextFromXMLFile(@fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
}
catch (WebException webEx)
{
MessageBox.Show(webEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}
For more C# tips and tricks, subscribe now
4 comments:
Excellent! Solved all my woes - Cheers.
Is there a limit to the size of the xmlcontent you can send via webrequest ?
You don't by chance know how to do this using VB rather than C#?
first thnx for this post.
but me i have a problem on this same topic,i want to send xml data to a page on an web server and to be redirected to the page that will receive this request.
Thanks
Post a Comment