
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 😀
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
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.
i need how to connect with user and server
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
enter the method name as “POST”
GET method does not work.
The error msg is “Cannot send a content-body with this verb-type”
what if I want to call a javascript function on a page?
like:
httpget(uri, “javascript:ChangeAcc()”);
happy programming 🙂
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();
}
}
thank you
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.
How would you implement it using a username and password?
how do i close the connections immediately? i am getting the 4 instances ….
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;
}
How do i post and retrieve data to/fro a remote MS SQL using the this http webserver
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″);
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
Can you please elaborate how to run this program in vs
Also is it necessary to install IIS to run this program?
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.
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.
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.
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
Thanks for your code. It’s very useful
Thanks Ali, very useful
Very Useful! What a pain in the ass the default WebRequest with POST parameters…
Thank you very much!
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.
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());
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.
thx, your code is very usefull, but how to make this webrequest class asyncronously ?
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.
thanks you so much!..
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”
{“The remote server returned an error: (500) Internal Server Error.”}
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
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
Great class man! really simple and got it working in a second! Thanks for your efforts!
what are the changes we need to do if we want to use it for a Windows Phone App
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
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
Thank you for the information and explanation.
Do you know how to “upload a file” using a POST request?
Thanks Ali for your Work !
can i use async for same method ??
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!
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.
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();
}
POST using
1) XML
How get response in XML
and
2) JSON
How get response in JSON
real world sampes?
Thank you very much.