guyS's WebLog

IShare, My DotNet Fingerprint

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;
}

Comments

shiningstar said:

I have a web project, which has two web applications.I am calling a webpage of one application from a page of another application.

It is displaying the page nicely from the other application. but now what I want is to call the methods of this page which I am displaying using HttpWebRequest and Response. right now it is going to the calling page for the control methods and thus, gives an exception.

# November 9, 2010 11:22 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)