Created
April 3, 2013 18:22
-
-
Save afreeland/5303782 to your computer and use it in GitHub Desktop.
C#: Web Request Class for REST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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