The MSDN Library has some good information on using WebRequest. Here is a starting link:
"Deriving from WebRequest" from .NET Framework Developer's Guide
Below is ithe C# function using WebRequest.
Some notes:
- The Method property is set to "POST" in code. A more generic version
would allow setting the Method verb to go with the protocol specified
in the URI by passing the verb to use.
- This function was created expecting http:// protocol, though WebRequest can handle others.
- The "using" objects is for the entire class, and has more entries
than are needed for this function. I did not check which are the
extras. WebRequest is in System.Net.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
/// <summary>
/// Method opens the specified URL, 'POST' the data string,
/// and returns the returned response from the url address.
/// </summary>
/// <param name="URL">URL to server application with http protocol</param>
/// <param name="POSTdata">data
string properly formated to POST to the specified URL.</param>
/// <returns>The response returned by the application at the URL location.</returns>
/// <history>
/// [mbb] 7/15/2004 Created
/// </history>
public string UrlPOST(string URL, string POSTdata)
{
StringBuilder rtnValue = new StringBuilder();
bool isValidParams = true;
// check for url
if (URL.Length < 10)
{
isValidParams = false;
throw new Exception("URL = '" + URL + "' is not a valid URL.");
}
else if (URL.IndexOf("://") <= 0)
{
isValidParams = false;
throw new Exception("URL = '" + URL + "' is not a valid URL. URL must
include protocol, e.g. 'http://'");
}
if (isValidParams)
{
WebResponse result = null;
try
{
// setup WebRequest object
WebRequest request = WebRequest.Create(URL);
request.Method = "POST";
request.Timeout = 3000;
request.ContentType = "application/x-www-form-urlencoded";
// add payload for POST to request stream
byte[] SomeBytes = null;
SomeBytes = Encoding.UTF8.GetBytes(POSTdata);
request.ContentLength = SomeBytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
// POST data and get response
result = request.GetResponse();
Stream receive = result.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader stream = new StreamReader(receive, encode);
char[] read = new char[256];
int count = stream.Read(read, 0, 256);
// read through response to clear buffers, etc.
while (count > 0)
{
string str = new string(read, 0, count);
rtnValue.Append(str);
count = stream.Read(read, 0, 256);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (!(result == null))
{
result.Close();
result = null;
}
}
}
return rtnValue.ToString();
}
}
Hope this is helpful.
mbb