forked from EdTrench/ASPWebAPIExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClass.cs
More file actions
122 lines (106 loc) · 2.5 KB
/
HttpClass.cs
File metadata and controls
122 lines (106 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Linq;
using System.Net.Cache;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using Serializer;
namespace Serializer
{
public enum SupportedHttpMethods
{
GET,
POST,
PUT,
DELETE
}
public class HttpClass : IDisposable
{
Uri _uri;
HttpMethod _httpMethod;
StringContent _content;
HttpClient _httpClient = new HttpClient();
Action _action;
HttpResponseMessage _httpResponseMessage;
public HttpClass(SupportedHttpMethods httpMethod, string uri, string content) : this(httpMethod,uri)
{
if (httpMethod == SupportedHttpMethods.POST || httpMethod == SupportedHttpMethods.PUT)
{
JObject.Parse(content);
_content = new StringContent(content);
_content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
}
else
{
throw new InvalidHttpMethodContentCombinationException();
}
}
public HttpClass(SupportedHttpMethods httpMethod, string uri)
{
_uri = new Uri(uri);
_httpMethod = new HttpMethod(httpMethod.ToString());
switch (httpMethod)
{
case SupportedHttpMethods.GET:
_action = get;
break;
case SupportedHttpMethods.POST:
_action = post;
break;
case SupportedHttpMethods.PUT:
_action = put;
break;
case SupportedHttpMethods.DELETE:
_action = delete;
break;
default:
throw new InvalidHttpMethodException();
}
}
public void Dispose()
{
}
public HttpResponseMessage GetHttpResponseMessage()
{
return _httpResponseMessage;
}
public string GetResponseContent()
{
if (_httpMethod.Method == SupportedHttpMethods.GET.ToString())
return _httpResponseMessage.Content.ReadAsStringAsync().Result;
return null;
}
public void Invoke()
{
_action.Invoke();
}
void delete()
{
_httpResponseMessage = _httpClient.DeleteAsync(_uri).Result;
}
void get()
{
_httpResponseMessage = _httpClient.GetAsync(_uri).Result;
}
void post()
{
_httpResponseMessage = _httpClient.PostAsync(_uri, _content).Result;
}
void put()
{
_httpResponseMessage = _httpClient.PutAsync(_uri, _content).Result;
}
}
public class InvalidHttpMethodContentCombinationException : Exception
{
public InvalidHttpMethodContentCombinationException() : base("When specifying content, either a POST or PUT must be used")
{
}
}
public class InvalidHttpMethodException : Exception
{
public InvalidHttpMethodException() : base("Only PUT, POST, GET and DELETE Methods are supported")
{
}
}
}