Saturday, September 6, 2008

Programatically making a Web Request

Scenario:
You want to read a web-page or file programatically.

Code:

private void AccessWeb(string siteURL) {
WebRequest request = WebRequest.Create(siteURL);
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "GET";

WebResponse response = request.GetResponse();
response.Close();
}
Also you can use HTTPWebRequest object

private void GetBookReview(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();

try
{
string request = "http://xml.amazon.com/onca/xml2?" +
"t=webservices-20&dev-t=[D1LKOL21AANCMO]&"+
"AsinSearch=" + textBoxASIN.Text +
"&mode=books&type=heavy&page=1&f=xml";

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(request);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

StreamReader s = new StreamReader
(resp.GetResponseStream(),Encoding.ASCII);

XmlDocument doc = new XmlDocument();
doc.LoadXml(s.ReadToEnd());

s.Close();

sb.Append("<HR><TABLE width='95%' align='center'>");

XmlNode salesRankNode = doc.SelectSingleNode("//SalesRank");
if(salesRankNode!=null)
sb.AppendFormat("<B>Sales Rank: {0}</B><BR><BR>",salesRankNode.InnerText);

XmlNodeList customerReviewNodes = doc.SelectNodes("//CustomerReview");
if(customerReviewNodes.Count>0)
{
foreach(XmlNode reviewNode in customerReviewNodes)
{
sb.AppendFormat("<B><U>Review (Rating {0}): {1}</U></B><BR>",
reviewNode.ChildNodes[0].InnerText,
reviewNode.ChildNodes[1].InnerText);
sb.AppendFormat("<I>{0}</I><BR><BR>",
reviewNode.ChildNodes[2].InnerText);
}
}

sb.Append("</DIV>");
sb.Append("</TABLE>");
}
catch(Exception ex)
{
throw new Excepion("Sorry, unable to retrieve the books!");
}
}

0 comments: