C# .NET: Send a Web Request and Return String of Results

11/26/2013 9:40:18 PM

The following takes an input Url and will make a web request and return a string with the web server's returned data. It uses the .NET System.Net.WebRequest. It accepts a Url, a post type, post data, and a timeout value.

public static string GetWebResponse(string url, string httpMethod, string postData = "", int timeOutInSeconds = 10)
{
	string responseData = "";

	try
	{
		httpMethod = httpMethod.ToUpper();

		System.Net.HttpWebRequest webRequest = null;
		System.IO.StreamWriter requestStreamWriter = null;

		webRequest = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
		webRequest.Method = httpMethod;
		webRequest.ServicePoint.Expect100Continue = false;
		//webRequest.UserAgent = "";
		webRequest.Timeout = timeOutInSeconds * 1000;

		if (webRequest.Method == "POST")
		{
			webRequest.ContentType = "application/x-www-form-urlencoded";

			requestStreamWriter = new System.IO.StreamWriter(webRequest.GetRequestStream());
			try
			{
				if (!string.IsNullOrEmpty(postData))
				{
					requestStreamWriter.Write(postData);
				}
			}
			catch
			{
				throw;
			}
			finally
			{
				requestStreamWriter.Close();
				requestStreamWriter = null;
			}
		}

		System.IO.StreamReader responseReader = null;
		try
		{
			responseReader = new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream());
			responseData = responseReader.ReadToEnd();
		}
		catch
		{
			throw;
		}
		finally
		{
			webRequest.GetResponse().GetResponseStream().Close();
			responseReader.Close();
			responseReader = null;
			webRequest = null;
		}

		webRequest = null;
	}
	catch (Exception ex)
	{
	}

	return responseData;
}