C#: HttpWebRequest example with error handling using C#

using System;

using System.IO;

using System.Net;

using System.Text;

 

public class HttpWebRequestTool

{

  public static void Main(String[] args)

  {

    if (args.Length < 2)

    {

      Console.WriteLine("Missing argument. Need a URL and a filename");

    }

    else

    {

      StreamWriter sWriter = new StreamWriter(args[1]);

      sWriter.Write(WRequest(args[0], "GET", ""));

      sWriter.Close();

    }

  }

 

  public static string WRequest(string URL, string method, string postData)

  {

    string responseData = "";

    try

    {

      System.Net.HttpWebRequest hwrequest =

        (System.Net.HttpWebRequest) System.Net.WebRequest.Create(URL);

      hwrequest.Accept = "*/*";

      hwrequest.AllowAutoRedirect = true;

      hwrequest.UserAgent = "http_requester/0.1";

      hwrequest.Timeout= 60000;

      hwrequest.Method = method;

      if (hwrequest.Method == "POST")

      {

        hwrequest.ContentType = "application/x-www-form-urlencoded";

        // Use UTF8Encoding instead of ASCIIEncoding for XML requests:

        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

        byte[] postByteArray = encoding.GetBytes(postData);

        hwrequest.ContentLength = postByteArray.Length;

        System.IO.Stream postStream = hwrequest.GetRequestStream();

        postStream.Write(postByteArray, 0, postByteArray.Length);

        postStream.Close();

      }

      System.Net.HttpWebResponse hwresponse =

        (System.Net.HttpWebResponse) hwrequest.GetResponse();

      if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)

      {

        System.IO.Stream responseStream = hwresponse.GetResponseStream();

        System.IO.StreamReader myStreamReader =

          new System.IO.StreamReader(responseStream);

        responseData = myStreamReader.ReadToEnd();

      }

      hwresponse.Close();

    }

    catch (Exception e)

    {

      responseData = "An error occurred: " + e.Message;

    }

    return responseData;

  }

}