• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Generate HTTP Requests using c#

Generate HTTP Requests using c#

December 21, 2010 by Rana Ahsan 48 Comments

c# Tutorials

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

Update: At the time of writing this article, I didn’t find any other useful library, why I created this very basic/simple wrapper class. However, there is now more advanced way to perform such operation using restsharp client. You can refer to this if you are about to perform complete http requests. However, still, the following simple class can help you understand the internal mechanism how a request constructed.

As I am going to provide a solution already, so I am not going to explain the internal mechanism in detail. But, feel free to explore the class if you want, it’s pretty straightforward. 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; } }
Code language: PHP (php)

Basic Understanding Of This Class:

So, as you can see, constructors can be of three different types. You must need to pass the URL. It will by default set the method as ‘GET’. If you need to use the ‘POST’ method, then please pass it as a second parameter. The third parameter is for passing the ‘data’, that you may want to post to the 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 error occurred 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 C# 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 parameterless function to receive the response data. So, all things to feed it are in the constructor call. There are three different types of constructors you can call. One with one parameter(web resource URL), it simply downloads the data of the web page. The 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). The third one, with 3 parameters(URL, method, and data).

For the URL parameter, you must have to use a valid URI. For the method parameter, you have to use “GET” or “POST” depending on your request type. The 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 add here. I will try to do so. Happy coding 😀

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: .net, c#, http

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Naim says

    March 19, 2011 at 4:21 am

    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

    Reply
    • Rana says

      March 21, 2011 at 5:06 am

      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.

      Reply
      • gokila says

        July 30, 2013 at 9:18 pm

        i need how to connect with user and server

        Reply
  2. Phil says

    April 3, 2011 at 5:36 pm

    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

    Reply
    • swamy says

      October 31, 2012 at 5:51 am

      enter the method name as “POST”

      Reply
  3. jason says

    April 6, 2011 at 1:45 am

    GET method does not work.

    The error msg is “Cannot send a content-body with this verb-type”

    Reply
  4. Daniel says

    April 17, 2011 at 7:56 am

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

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

    happy programming 🙂

    Reply
  5. janmu says

    June 8, 2011 at 2:50 am

    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();
    }

    }

    Reply
    • Максим Киселёв says

      December 15, 2014 at 7:46 pm

      thank you

      Reply
  6. asif says

    July 26, 2011 at 12:51 am

    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.

    Reply
  7. Jack says

    January 25, 2012 at 6:43 am

    How would you implement it using a username and password?

    Reply
  8. keerthy says

    March 5, 2012 at 4:45 am

    how do i close the connections immediately? i am getting the 4 instances ….

    Reply
  9. ftf says

    April 26, 2012 at 8:22 am

    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;
    }

    Reply
  10. John Bradford says

    July 26, 2012 at 3:32 am

    How do i post and retrieve data to/fro a remote MS SQL using the this http webserver

    Reply
  11. Trevor McIntire says

    August 11, 2012 at 10:04 am

    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″);

    Reply
  12. Eric Collins says

    August 28, 2012 at 7:41 am

    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

    Reply
  13. Andy says

    January 15, 2013 at 12:46 am

    Can you please elaborate how to run this program in vs
    Also is it necessary to install IIS to run this program?

    Reply
    • Md. Ali Ahsan Rana says

      January 15, 2013 at 2:13 am

      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.

      Reply
  14. Leandro Farias says

    January 21, 2013 at 7:17 am

    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.

    Reply
    • Md. Ali Ahsan Rana says

      January 22, 2013 at 4:18 am

      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.

      Reply
  15. Gaurav Chhabra says

    February 8, 2013 at 10:27 am

    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

    Reply
  16. elvloggero says

    February 8, 2013 at 3:32 pm

    Thanks for your code. It’s very useful

    Reply
  17. Carlos Rueckert says

    February 14, 2013 at 11:03 pm

    Thanks Ali, very useful

    Reply
  18. Roy says

    March 4, 2013 at 10:11 am

    Very Useful! What a pain in the ass the default WebRequest with POST parameters…

    Thank you very much!

    Reply
  19. mandeep says

    April 8, 2013 at 12:20 am

    Nice article. As per my research on this topic, I have seen that we can improve the security concerns regarding GET request by using HTTPS protocol.

    Reply
  20. Code says

    May 11, 2013 at 10:03 am

    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());

    Reply
    • Md Ali Ahsan Rana says

      May 23, 2013 at 12:51 pm

      as far I can track, you need to provide “GET” instead of “POST”(as all variables in url are passed in GET method). May be the server only accepts GET requests.

      Reply
  21. Moch. Firmansyah says

    October 9, 2013 at 9:53 am

    thx, your code is very usefull, but how to make this webrequest class asyncronously ?

    Reply
  22. Rogala says

    April 30, 2014 at 12:34 pm

    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.

    Reply
  23. Miguel says

    June 9, 2014 at 12:01 pm

    thanks you so much!..

    Reply
  24. Bryan says

    July 27, 2014 at 9:48 pm

    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”

    Reply
  25. sudeep says

    November 19, 2014 at 4:06 am

    {“The remote server returned an error: (500) Internal Server Error.”}

    Reply
  26. Harold Casimina says

    November 29, 2014 at 2:12 am

    Dear Ali Ahsan,

    How can I use this in a multiple call?

    To give you the idea. I created a 2 method that calls different data.

    For instance:

    checkExisting_data() – for getting hours list
    addComboList() – for getting projects list

    But when I put this both on the Form Load, only one method is working and the other is not but when I commented the first one the second method works. So i guess there is nothing wrong with my method

    //Sample Code
    http://pastebin.com/bzWczKXc

    Please advise!
    Thank you in advance

    Reply
  27. VR says

    December 30, 2014 at 2:58 pm

    This script does not RUN.. any ideas. also i want to know how i can get the URL connect to display TRUE as in connection is TRUE .

    That way i know the code works and POST.
    THis is what i have but it does not work.

    I want to POST to URL with the STRING like:
    http://www.myurl.com/bin/usernamehere.passwordhere.morestuffhere.timeanddatehere.

    can anyone help.?

    Code:
    http://pastebin.com/Dnx7Dpam

    Reply
  28. nickjwparkNick says

    January 18, 2015 at 6:42 am

    Great class man! really simple and got it working in a second! Thanks for your efforts!

    Reply
  29. manojitballav says

    June 7, 2015 at 7:04 pm

    what are the changes we need to do if we want to use it for a Windows Phone App

    Reply
  30. raj says

    August 7, 2015 at 12:27 am

    i want to send an http request.. but i want that page of this http request is not show to the user….
    please solve my problem

    Reply
  31. emma OJ says

    October 26, 2015 at 5:47 pm

    I need to send a request to a payment switch with the following parameters in asp.net C# and receive an json response, any idea how

    Sample Request (JSON)
    GET
    https://stageserv.interswitchng.com/test_paydirect/api/v1/gettransaction.json?productid=21&transactionreference=8421941122&amount=300000 HTTP/1.1
    UserAgent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.239)
    Hash: F6FF2E22F99D93DDDA52D71811FD92B3A71FA1968A66216E0D310DAD

    Sample Response (JSON)
    HTTP/1.0 200 OK
    Date: Tue, 30 Oct 2012 16:12:17 GMT
    Content-Type: application/json; charset=utf-8
    Content-Length: 333
    {“Amount”:300000,”CardNumber”:”6055″,”MerchantReference”:”8421941122″,”PaymentReference”:”ZIB|WEB|VNA|15-10-2012|015933″, “RetrievalReferenceNumber”:”000000538268″, “LeadBankCbnCode”:null, “LeadBankName”:null, “SplitAccounts[],”TransactionDate”:”2012-10-15T11:07:54.547″,”ResponseCode”:”00″,”ResponseDescription”:”Approved Successful”}

    Please help

    Reply
  32. Juan Ramos Suyón says

    December 23, 2015 at 9:45 pm

    Thank you for the information and explanation.
    Do you know how to “upload a file” using a POST request?

    Reply
  33. Ivan KL says

    January 26, 2016 at 4:27 pm

    Thanks Ali for your Work !

    Reply
  34. Lucky says

    March 15, 2016 at 5:20 am

    can i use async for same method ??

    Reply
  35. Axil says

    December 14, 2016 at 9:42 am

    Super simple, and complete! Sometimes it’s difficult to remember which order C# objects need to be created to get a good response. Your article was very helpful in reminding me how to properly get content into the right part of the response / request objects in C#. Thanks!

    Reply
  36. Ravi Walde says

    January 3, 2017 at 9:18 am

    Dear Sir,
    How to use this wrapper class in my webpage .
    i have returmUrl.Aspx and .Cs page.
    please tell me the procedure for use of this wrapper class for handling HTTP get/Post request from payment gatway.
    How it will usefull for pickup response from payment gayway.
    waiting hopefully.
    thank in advance.

    Reply
  37. Susan says

    April 14, 2017 at 2:32 am

    Hi,

    Below is my code and they are pretty simple. However, I’m encountering (500) Internal Server Error from this line.
    HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();

    public void GetRequestID(string atoken)
    {
    string webpage_data = “INC000003785314”;
    string webpage = “https://arstest.micron.com:9443/api/arsys/v1/entry/HPD%3AIncidentInterface/?fields=values(Request ID)&q=’Incident Number’%3D”;

    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] data = encoding.GetBytes(webpage_data);
    webpage = webpage + webpage_data;
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(webpage);

    myRequest.Credentials = CredentialCache.DefaultCredentials;
    myRequest.Method = “GET”;
    myRequest.ContentType = “application/json”;
    myRequest.Headers.Add(“Authorization”, atoken);

    HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
    Stream receive_stream = response.GetResponseStream();
    StreamReader read_stream = new StreamReader(receive_stream, Encoding.UTF8);

    string str = read_stream.ReadToEnd();

    response.Close();
    read_stream.Close();
    }

    Reply
  38. Pregunton Cojonero says

    October 29, 2017 at 11:11 am

    POST using

    1) XML

    How get response in XML
    and

    2) JSON
    How get response in JSON

    real world sampes?

    Reply
  39. Armorik says

    March 26, 2021 at 10:13 am

    Thank you very much.

    Reply

Trackbacks

  1. C# Tutorial For Retrieving Facebook Api Access Token | codesamplez.com says:
    December 28, 2010 at 3:30 am

    […] two custom class, one is MYWebRequest, that I have discussed before while showing way of creating http request using c sharp; Another is MyFB, a simple class that utilizes facebook api library and meet my custom […]

    Reply
  2. Facebook Graph Api C# Tutorial | codesamplez.com says:
    January 20, 2011 at 2:41 am

    […] . Here, I will like to inform you that, this sdk in not a must, as that can be done using simple http request in c#. But in case of authorized api calls, this sdk will help a lot for sure.Moreover, its better to use […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • LinQ To SQL Database Update Operations In C#
    LinQ To SQL Database Update Operations In C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023