Home
Manage Your Code
Snippet: Simple HTTP Web Request - POST (C#)
Title: Simple HTTP Web Request - POST Language: C#
Description: A simple method implementing POST Views: 534
Author: Paul Ward Date Added: 11/11/2011
Copy Code  
1public string UploadMessage ( string messageXml, string uri )
2{
3    string result = String.Empty;
4    byte[] messageBytes = Encoding.UTF8.GetBytes( messageXml );
5
6            
7    HttpWebRequest request = (HttpWebRequest) WebRequest.Create( uri );
8    request.UserAgent = "Transport Client";
9    request.Method = "POST";
10    request.ContentType = "text/xml";
11    request.ContentLength = messageBytes.Length;
12
13
14    using ( Stream dataStream = request.GetRequestStream( ) )
15    {
16        dataStream.Write( messageBytes, 0, messageBytes.Length );
17    }
18
19
20    using ( HttpWebResponse response = (HttpWebResponse)request.GetResponse( ) )
21    {
22        if ( response.StatusCode != HttpStatusCode.OK )
23        {
24            throw new ApplicationException( String.Format( "Data POST Failure. Response code : {0} ({1})",
25                response.StatusCode, response.StatusDescription ) );
26        }
27
28        Stream dataStream = response.GetResponseStream( );
29
30        StreamReader reader = new StreamReader( dataStream );
31
32        result = reader.ReadToEnd( );
33
34        reader.Close( );
35    }
36
37
38    return result;
39}
Usage
string response = UploadMessage("POST STRING", "http://blah.com");
Notes
System.Net