-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuinHttp.cs
More file actions
261 lines (224 loc) · 9.42 KB
/
GuinHttp.cs
File metadata and controls
261 lines (224 loc) · 9.42 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
using GuinHttp.Attributes.HttpContentType;
using GuinHttp.Attributes.HttpHeader;
using GuinHttp.Attributes.HttpMethod;
using GuinHttp.Attributes.HttpParameter;
using GuinHttp.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
namespace GuinHttp
{
public class GuinHttp
{
#region Property
public string BaseUrl { get; private set; }
public int Timeout { get; private set; }
#endregion
#region Constructor
private GuinHttp(string baseUrl)
{
BaseUrl = baseUrl;
}
public static GuinHttpBuilder Builder(string baseUrl)
{
return new GuinHttpBuilder(baseUrl);
}
public class GuinHttpBuilder
{
private GuinHttp GuinHttp;
public GuinHttpBuilder(string baseUrl)
{
GuinHttp = new GuinHttp(baseUrl);
}
public GuinHttpBuilder SetTimeOut(int timeout)
{
GuinHttp.Timeout = timeout;
return this;
}
public GuinHttp Build()
{
return GuinHttp;
}
}
#endregion
#region Event
public delegate void ExceptionCatchedHandler(object sender, Exception exception, string memo);
public event ExceptionCatchedHandler ExceptionCatched;
#endregion
#region Method
public string RequestApi(object anonymousObj, MethodBase caller)
{
string contentType = caller.GetAttributeValue((HttpContentTypeAttribute t) => t.Value);
string apiPath = caller.GetAttributeValue((HttpMethodAttribute t) => t.ApiPath);
string method = caller.GetAttributeValue((HttpMethodAttribute t) => t.Value);
string[] headers = caller.GetAttributeValue((HttpHeadersAttribute t) => t.Value);
byte[] postData = { };
var query = string.Empty;
//anonymous 타입의 클래스와 이전 메소드의 parameterInfo를 이용해 RequestParam타입을 구분합니다.
var anonymousObjProperties = anonymousObj.GetType().GetProperties();
var callerParameters = caller.GetParameters();
//Paramer Type 별로 그룹핑 해줍니다.
var propertyGroup = from prop in anonymousObjProperties
group prop by callerParameters.Where(param => param.Name == prop.Name).FirstOrDefault().GetAttributeValue((HttpParameterAttribute at) => at.GetType()) into groupingResult
select new { Key = groupingResult.Key, Value = groupingResult };
foreach (var group in propertyGroup)
{
switch (group.Key)
{
case Type t when t == typeof(QueryAttribute):
query = GetQuery(anonymousObj, group.Value);
break;
case Type t when t == typeof(PathAttribute):
apiPath = GetPathVariable(apiPath, anonymousObj, group.Value);
break;
case Type t when t == typeof(BodyAttribute):
if (caller.GetCustomAttributes(typeof(HttpContentTypeAttribute), true).FirstOrDefault() is JsonBodyAttribute)
postData = GetJsonBody(anonymousObj, group.Value);
else if (caller.GetCustomAttributes(typeof(HttpContentTypeAttribute), true).FirstOrDefault() is FormUrlEncodedAttribute)
postData = GetFormUrlEncodedBody(anonymousObj, group.Value);
break;
default:
break;
}
}
var request = WebRequest.Create($"{BaseUrl}{apiPath}{query}") as HttpWebRequest;
request.Method = method;
request.Timeout = Timeout;
request.ContentType = contentType;
request.Headers = GetHeaderCollection(headers);
try
{
if (postData != null && postData.Length > 0)
{
request.ContentLength = postData.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(postData, 0, postData.Length);
}
}
}
catch (Exception e)
{
ExceptionCatched?.Invoke(this, e, $"{request?.RequestUri} body 생성 도중 오류");
return e.Message;
}
return GetAPIResponse(request);
}
private string GetQuery(object anonymousObj, IEnumerable<PropertyInfo> properties)
{
return Util.JoinAdvanced("?", "&"
, properties
, property =>
{
if (property.GetValue(anonymousObj, null) is List<string>)
{
return Util.JoinAdvanced("&", property.GetValue(anonymousObj, null) as List<string>, s => $"{property.Name}={HttpUtility.UrlEncode(s)}");
}
return $"{property.Name}={HttpUtility.UrlEncode(property.GetValue(anonymousObj, null)?.ToString())}";
}
);
}
private string GetPathVariable(string apiPath, object anonymousObj, IEnumerable<PropertyInfo> properties)
{
foreach (var property in properties)
{
apiPath = apiPath.Replace($"{{{property.Name}}}", $"{HttpUtility.UrlEncode(property.GetValue(anonymousObj, null)?.ToString())}");
}
return apiPath;
}
private byte[] GetJsonBody(object anonymousObj, IEnumerable<PropertyInfo> properties)
{
byte[] body = { };
foreach (var property in properties)
{
var propertyData = property.GetValue(anonymousObj, null);
if (propertyData != null)
{
//null들어갈시 string "null" 반환
var json = JsonConvert.SerializeObject(propertyData);
var data = Encoding.UTF8.GetBytes(json);
body = Util.CombineByteArray(body, data);
}
}
return body;
}
private byte[] GetFormUrlEncodedBody(object anonymousObj, IEnumerable<PropertyInfo> properties)
{
byte[] body = { };
foreach (var property in properties)
{
var bodyItem = property.GetValue(anonymousObj, null);
var bodyItemProperties = bodyItem.GetType().GetProperties();
var formUrlEncodedBodyItem = Util.JoinAdvanced("&"
, bodyItemProperties
, bodyItemProperty =>
{
if (bodyItemProperty.GetValue(bodyItem, null) is List<string>)
{
return Util.JoinAdvanced("&", bodyItemProperty.GetValue(bodyItem, null) as List<string>, s => $"{bodyItemProperty.Name}={HttpUtility.UrlEncode(s)}");
}
return $"{bodyItemProperty.Name}={HttpUtility.UrlEncode(bodyItemProperty.GetValue(bodyItem, null)?.ToString())}";
}
);
var data = Encoding.UTF8.GetBytes(formUrlEncodedBodyItem);
body = Util.CombineByteArray(body, data);
}
return body;
}
private WebHeaderCollection GetHeaderCollection(string[] headers)
{
WebHeaderCollection headerCollection = new WebHeaderCollection();
headers?.ToList().ForEach(s =>
{
string[] pair = s.Split(':');
if (pair.Length == 2)
headerCollection.Add(pair[0].Trim(), pair[1].Trim());
}) ;
return headerCollection;
}
private string GetAPIResponse (HttpWebRequest request)
{
string result = string.Empty;
HttpWebResponse response = null;
Exception exception = null;
bool exceptionCatched = false;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
result = we.Message;
exceptionCatched = true;
exception = we;
}
finally
{
if (response != null)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
var streamResult = streamReader.ReadToEnd();
result = string.IsNullOrEmpty(streamResult) ? result : streamResult;
}
}
}
}
if (exceptionCatched)
{
ExceptionCatched?.Invoke(this, exception, $"{request?.RequestUri} {result}");
}
return result;
}
#endregion
}
}