.NET: How to Make HTTP Request and Get Response
There are so many ways to query external url in .NET, people can use so many approaches and .NET Framework classes available - it's crazy. Quering external urls via HTTP today is a common task many developers facing.
There are many REST (or other types of) open APIs created by external services.
Below I decided to post an example of how to do it the right way (as far as I can see it). This schematic function supports both POST and GET requests, highly scalable and the most important - it is designed as low level infrastructure function (i.e. uses simple types and bubbles exceptions).
public string GetHttpResponse(string requestUrl, byte[] data)
{
// declare objects
string responseData = String.Empty;
HttpWebRequest req = null;
HttpWebResponse resp = null;
StreamReader strmReader = null;
try
{
req = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
// set HttpWebRequest properties here (Method, ContentType, etc)
// some code
// in case of POST you need to post data
if ((data != null) && (data.Length > 0))
{
using (Stream strm = req.GetRequestStream())
{
strm.Write(data, 0, data.Length);
}
}
resp = (HttpWebResponse)req.GetResponse();
strmReader = new StreamReader(resp.GetResponseStream());
responseData = strmReader.ReadToEnd().Trim();
}
catch (Exception ex)
{
throw;
}
finally
{
if (req != null)
{
req = null;
}
if (resp != null)
{
resp.Close();
resp = null;
}
}
return responseData;
}
P.S. - HttpWebRequest proved to be the most reliable for me.
Enjoy
Friday, August 29, 2008 12:34 AM