Skip to content

Instantly share code, notes, and snippets.

@afreeland
Created April 3, 2013 18:22
Show Gist options
  • Save afreeland/5303782 to your computer and use it in GitHub Desktop.
Save afreeland/5303782 to your computer and use it in GitHub Desktop.
C#: Web Request Class for REST
public class HTTP
{
public enum Method
{
GET = 3,
POST = 0,
PUT = 1,
DELETE = 2
}
public class Request
{
private WebRequest _request;
private Stream _stream;
private String _status;
public String Status
{
get { return _status; }
set { _status = value; }
}
public Request(string url)
{
// Create a request using a URL
_request = WebRequest.Create(url);
}
public Request(string url, HTTP.Method HTTPMethod) :this(url)
{
// Set the method
switch (HTTPMethod)
{
case Method.GET:
_request.Method = "GET";
break;
case Method.POST:
_request.Method = "POST";
break;
case Method.PUT:
_request.Method = "PUT";
break;
case Method.DELETE:
_request.Method = "DELETE";
break;
default:
_request.Method = "GET";
break;
}
}
public APIResponse GetResponse()
{
// Get original resposne
WebResponse response = _request.GetResponse();
this.Status = ((HttpWebResponse)response).StatusDescription;
// Get the stream containing all content returned by request
_stream = response.GetResponseStream();
// Open the stream using a StreamReader
StreamReader reader = new StreamReader(_stream);
// Read entire content
String fullResponse = reader.ReadToEnd();
// Clean up
reader.Close();
_stream.Close();
response.Close();
return JSON.Deserialize<APIResponse>(fullResponse);
}
}
}
// Can be called like this
HTTP.Request req = new HTTP.Request(url, HTTP.Method.GET);
n.Framework.v1.WebServices.APIResponse k = req.GetResponse();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment