Generate HTTP Requests using c#


 Generate HTTP Requests using c#  
 


In several applications, its required to create some requests(either get or post ) on a web resource and process the received data from the server script itself. In popular scripting language php, curl library helps to do such works perfectly. Who are using c# and .net platform for developing web applications, they also need to have such facilities. Luckily, there are already some built-in classes in .net framework to give native supports. However, this native support of performing HTTP requests using C# are very raw and can be generalized as a wrapper. I will provide c# code sample of a complete wrapper class that you can reuse on your application with minimal customization.

As I am going to provide a solution already, so I am not going to explain internal mechanism in details. But, feel free to explore the class if you want, its pretty straight forward. I will how to use that class and what format to follow to pass parameters.

Alternatively, you can fork a copy from github also. The github url for this is: https://github.com/ranacseruet/webrequest-csharp

Here you go with the complete code of the class:

public class MyWebRequest
        {
            private WebRequest request;
            private Stream dataStream;

            private string status;

            public String Status
            {
                get
                {
                    return status;
                }
                set
                {
                    status = value;
                }
            }

            public MyWebRequest(string url)
            {
                // Create a request using a URL that can receive a post.

                request = WebRequest.Create(url);
            }

            public MyWebRequest(string url, string method)
                : this(url)
            {

                if (method.Equals("GET") || method.Equals("POST"))
                {
                    // Set the Method property of the request to POST.
                    request.Method = method;
                }
                else
                {
                    throw new Exception("Invalid Method Type");
                }
            }

            public MyWebRequest(string url, string method, string data)
                : this(url, method)
            {

                // Create POST data and convert it to a byte array.
                string postData = data;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";

                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;

                // Get the request stream.
                dataStream = request.GetRequestStream();

                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);

                // Close the Stream object.
                dataStream.Close();

            }

            public string GetResponse()
            {
                // Get the original response.
                WebResponse response = request.GetResponse();

                this.Status = ((HttpWebResponse)response).StatusDescription;

                // Get the stream containing all content returned by the requested server.
                dataStream = response.GetResponseStream();

                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);

                // Read the content fully up to the end.
                string responseFromServer = reader.ReadToEnd();

                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();

                return responseFromServer;
            }

        }

So, as you can see, constructor can be of three different types. You must need to pass the URL. It will by default set method as ‘GET’. If you need to use ‘POST’ method, then please pass it as second parameter. Third parameter is for pass the ‘data’, that you may want to post to server. And the “GetResponse()” method will return the result in plain text format, so you need to process it as per your need. You can check whether any errror occured or not by using the “Status” property.

Just to clear a confusion from many readers, it doesn’t matter what kind of application you are working on, either desktop application or Asp.NET web application, this class can be used in the same way for both types. Cheers!

Using This HTTP Request Class:

Implementing this class to an application is quite easy. First you have to create an instance of the class and then call a parameter less function to receive the response data. So, all things to feed it is in the constructor calling. There are three different type of constructor you can call. One with one parameter(web resource url), it simply download the data of the web page. Second one with 2 parameters(url and method of request,get or post), actually, this is the one, you won’t use anytime for this version of the class, as without data post type is meaning less(I have kept it to be it as modular and so that calling constructor can be flexible enough and other parameters also can be set by creating properties if needed). Third one, with 3 parameters(url, method and data).

For url parameter, you must have to use a valid uri. For method parameter, you have to use “GET” or “POST” depending on your request type. Third parameter should be all data url encoded should be like this format:
“variable1=value1&variable2=value2″

Here is a sample code snippet to make a complete request and get the string response:

//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.yourdomain.com","POST","a=value1&b=value2");
//show the response string on the console screen.
Console.WriteLine(myRequest.GetResponse());

This is it, Let me know if you are having any complexities here and also if you want any more features to added here. I will try to do so. Happy coding :D

Comments

  1. says

    I am trying to make call to pages in facebook Graph API and retrive in my application. Do you suggest me to go through install Facebook C# SDK or to use the code above for accessing.

    Kind regards,
    Naim

    • says

      Depends on the spec domain. If you are creating an fully Facebook based application, then I will suggest you to use the facebooksdk. For simple usage(and to understand better how they works), you can go with the manual approaches that i have discussed in few posts. Hope this helps.

  2. Phil says

    Hi Rana,

    Thanks for you post.
    I had a error at line 57 dataStream = request.GetRequestStream();
    The error msg is “Cannot send a content-body with this verb-type”
    Is there any extra I need to do?
    Thanks

    Warm Regards
    Phil

  3. Daniel says

    what if I want to call a javascript function on a page?
    like:

    httpget(uri, “javascript:ChangeAcc()”);

    happy programming :)

  4. janmu says

    Modification for GET request working

    public MyWebRequest(string url, string method, string data)
    : this(url, method)
    {

    if (request.Method == “POST”)
    {
    // Create POST data and convert it to a byte array.
    byte[] byteArray = Encoding.UTF8.GetBytes(data);

    // Set the ContentType property of the WebRequest.
    request.ContentType = “application/x-www-form-urlencoded”;

    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    // Get the request stream.
    dataStream = request.GetRequestStream();

    // Write the data to the request stream.
    dataStream.Write(byteArray, 0, byteArray.Length);

    // Close the Stream object.
    dataStream.Close();
    }
    else
    {
    String finalUrl = string.Format(“{0}{1}”, url, “?” + data);
    request = WebRequest.Create(finalUrl);

    WebResponse response = request.GetResponse();

    //Now, we read the response (the string), and output it.
    dataStream = response.GetResponseStream();
    }

    }

  5. asif says

    Dear Sir,
    I have 2 doubts

    1. I am not getting should I use same url or replace it to my domain url which I dont have.
    http://www.yourdomain.com

    2.
    Getting error at below line
    public string GetResponse()

    {

    // Get the original response.

    WebResponse response = request.GetResponse();

    Error is
    WebException was unhandled by user code
    “The remote server returned an error: (405) Method Not Allowed.”

    Kindly help me to resolve it.

  6. ftf says

    it is not necessary to close a stream when you’ve already called Close() on its assigned StreamWriter/Reader. it does it for you automatically.

    it’s also a good practice to use the “using” keyword when working with streams.
    for instance if we have a stream ‘s’ and string ‘stuff’

    using (StreamWriter sw = new StreamWriter (s) )
    {
    sw.Write (stuff);
    }

    once the end of the block is reached, the StreamWriter object gets disposed, calling Close() on itself before that happens and in turn closing the underlying stream as well.

    I’m using the following convenience methods to write to and read from streams when working with http requests, feel free to use them yourself.

    public static void StringToStream(Stream stream, string content)
    {
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.Write(content);
    }
    }

    public static string StringFromStream(Stream stream)
    {
    string content;
    using (StreamReader reader = new StreamReader(stream))
    {
    content = reader.ReadToEnd();
    }
    return content;
    }

  7. says

    Hello. I’m getting:
    Cannon implicitly convert type ‘MyWebRequest’ to ‘System.Net.WebRequest’, On WebRequest myRequest = new MyWebRequest(“http://www.minecraft.net”,”POST”,”a=value1&b=value2″);

  8. Eric Collins says

    It would be very helpful to see what ‘using’ statements you would need in both the example code and the class that you created.

    I find so many examples were people give code but do not give the using statements to know which areas of the .net library to call. This would be extremely helpful for people are are just starting out and don’t have common library’s or using statements memorized.

    Thank you

    • says

      You can run it on either a desktop application or on web application. This will facilitate you in cases, where your application itself need to request to other external web http get or post request and process the response. You don’t need to install iis.

  9. Leandro Farias says

    Hi, im need get one request of another website, they send to me via POST, but i dont know how i get in my page, they send 2 parameters:
    Like that: notificationCode=766B9C-AD4B044B04DA-77742F5FA653-E1AB24
    notificationType=transaction

    Im using C#

    What i go put on pageload to get this parameters?

    Thanks for all help.

    • says

      Hi, you can handle them is the same way you handle your own site’s GET/POST request. Just need to grab the ‘Request.Params["SomeID"]‘ or Request.Querystring(“parameter1″) in your c# code, depending what type of http request they are sending to your application. Hope this helps.

  10. Gaurav Chhabra says

    Hello When i am using this code then i am getting NULL value in return when i am accessing my PHP file directly from Browser.

    and even in OUTPUT window of VS, it display just the value of a only that is “Value1″ nothing else.

    my client side application is in C# using help from your code
    and my Service Side application is in PHP and the statement i am using in my PHP file is

    and one more consultation, i would like to post data that the client will enter in Textbox and i tried to put that in query but failed.

    So, it would be really appreciable if you can help me for that also along with the NULL value Return

  11. Code says

    I want to get response from this url:
    https://testapi.internet.bs/Domain/Check?Domain=HASANUDDIN.INFO&ApiKey=testapi&Password=testpass

    Note: this the original web http://www.internetbs.net/ResellerRegistrarDomainNameAPI/api/01_domain_related/01_domain_check

    but i got this error message:
    “The operation has timed out”

    Could you tell me is there something wrong from my code, here is my code:
    //create the constructor with post type and few data
    MyWebRequest myRequest = new MyWebRequest(“https://testapi.internet.bs/Domain/Check”, “POST”, “Domain=HASANUDDIN.INFO&ApiKey=testapi&Password=testpass”);
    //show the response string on the console screen.
    Console.WriteLine(myRequest.GetResponse());

  12. Rogala says

    Good post to get the initial structure, but as mentioned in previous comments, this only works if a response of 200 is received, but errors out on other responses. This is not hard to add, but just don’t implement into a solution without adding necessary additional code.

  13. Bryan says

    Hi,

    How could you use this to replace this Curl statement

    curl -H “X-Auth-User: bryanoliver” -H “X-Auth-Expires: 1406485297″ -H “X-Auth-Key: 946ddd08f5fbcb3ddb0c91e3785f0630″ “-H” “Accept: application/xml” “https://acb7b192c688.cloud.elementaltechnologies.com/api/jobs/1″

Trackbacks

Leave a Reply