Monday, February 22, 2010

C# - example of HTTP call

1. Sample to use HTTP GET protocol

using system.net;

{
....
string strURL;
strURL = "http://xxxx/default.aspx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);

request.Method = "GET";
try
{
using (WebResponse wr = request.GetResponse())
{
Stream strm = wr.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string line;

while ((line = sr.ReadLine()) != null)
{
MessageBox.Show(line.ToString());
}
strm.Close();
wr.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
....
}

2. Example of reading content of a file through URL

string strURL = "http://xxx/test.html";
string rl = "";
string strContent = "";

try
{
WebRequest myReq = WebRequest.Create(strURL);
WebResponse myRes = myReq.GetResponse();
Stream resStream = myRes.GetResponseStream();
StreamReader sr = new StreamReader(resStream, Encoding.Default);
StringBuilder sb = new StringBuilder();

while ((rl = sr.ReadLine()) != null)
{
sb.Append(rl);
}
strContent = sb.ToString();
myRes.Close();
}

No comments: