Calling web pages using HttpWebRequest
I use the following method when I had to call an Asp web page which return to me the result as Xml, from my Web Services. It was done in order to externalize the services from an existing DNA application to a Smart Client.
public static string GetABHttpRequest(StringBuilder data, string sourcePath)
{
Stream aStream = null;
try
{
int timeOut = 10000;
//get timeOut from config if exists
if (ConfigurationSettings.AppSettings["ServiceTimeOut"] != null &&
ConfigurationSettings.AppSettings["ServiceTimeOut"] != string.Empty)
timeOut = int.Parse(ConfigurationSettings.AppSettings["ServiceTimeOut"]);
//Send POST request AB asp web page
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sourcePath);
req.Method = "POST";
req.ContentType = "text/xml";
req.Timeout = timeOut;
req.Credentials = CredentialCache.DefaultCredentials;
if (data.Length > 0)
{
req.ContentLength = data.Length;
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write(data.ToString());
sw.Flush();
sw.Close();
}
// Create The Response Object And Fill It By Sending The Request;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
aStream = response.GetResponseStream();
StreamReader sr = new StreamReader(aStream);
StringBuilder sbOutput = new StringBuilder();
char[] buffer = new char[1024];
int r;
while( (r=sr.Read(buffer, 0, buffer.Length)) > 0 )
sbOutput.Append(buffer, 0, r);
return sbOutput.ToString();
}
catch (WebException ex)
{
//TODO: handle exception
}
catch (Exception ex)
{
//TODO: handle exception
}
finally
{
aStream.Close();
}
return string.Empty;
}