Many times, you might want to include data in your Web request that must be posted to a remote server. This data is likely to include form data that you want to post to a server, and this form data must be processed before any data can be returned. The code in Listing 13.7 shows you how to add POST data to your WebRequest. Listing 13.7 This Code Shows How to Post Data in a Request.try { WebRequest req = WebRequest.Create( strURL ); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] SomeBytes = null; SomeBytes = Encoding.UTF8.GetBytes( strPostData ); req.ContentLength = SomeBytes.Length; Stream newStream = req.GetRequestStream(); newStream.Write( SomeBytes, 0, SomeBytes.Length ); newStream.Close(); WebResponse result = req.GetResponse(); Stream ReceiveStream = result.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader sr = new StreamReader( ReceiveStream, encode ); Char[] ReadBuffer = new Char[256]; int nCount = sr.Read( ReadBuffer, 0, 256 ); while( nCount > 0 ) { String str = new String( ReadBuffer, 0, nCount ); nCount = sr.Read( ReadBuffer, 0, 256 ); } } catch( Exception ex ) { // Handle the exception here } |