RestClient.cs
6.48 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
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace MoyaAdminLib
{
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
public class RestClient
{
public string EndPoint { get; set; }
public HttpVerb Method { get; set; }
public string ContentType { get; set; }
public string PostData { get; set; }
public static string ApiApplicationKey { get; set; }
public static string ApiUser { get; set; }
public static string ApiPass { get; set; }
public static string ApiURL { get; set; }
public RestClient()
{
EndPoint = ApiURL;
Method = HttpVerb.GET;
ContentType = "application/json";
PostData = "";
}
public RestClient(string endpoint)
{
EndPoint = endpoint;
Method = HttpVerb.GET;
ContentType = "application/json";
PostData = "";
}
public RestClient(string endpoint, HttpVerb method)
{
EndPoint = endpoint;
Method = method;
ContentType = "application/json";
PostData = "";
}
public RestClient(string endpoint, HttpVerb method, string postData)
{
EndPoint = endpoint;
Method = method;
ContentType = "application/json";
PostData = postData;
}
private static string CalculateSHA1(string text)
{
// Convert the input string to a byte array
var buffer = Encoding.GetEncoding("iso-8859-1").GetBytes(text);
// In doing your test, you won't want to re-initialize like this every time you test a
// string.
var cryptoTransformSha1 = new SHA1CryptoServiceProvider();
// The replace won't be necessary for your tests so long as you are consistent in what
// you compare.
var hash = BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "").ToLower();
return hash;
}
private static int ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
var span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return (int)span.TotalSeconds;
}
public static string GetRequestURL(string server, string queryPath, string getparms)
{
var timestamp = ConvertToTimestamp(DateTime.Now);
var hash = CalculateSHA1("/" + queryPath + "+" + ApiApplicationKey + "+" + ApiUser + "+" + timestamp + "+" + ApiPass);
if (!string.IsNullOrEmpty(getparms))
getparms = getparms + "&";
var url = server + "/rest/" + queryPath + "?";
if (getparms != null)
url += getparms;
url += "appkey=" + ApiApplicationKey + "&appuser=" + ApiUser + "&appstamp=" + timestamp + "&appmac=" + hash;
Console.WriteLine(url);
return url;
}
public static string GetRequestURL(string server, string queryPath)
{
return GetRequestURL(server, queryPath, null);
}
public string MakeRequest(string queryPath)
{
return MakeRequest(queryPath, null);
}
public string MakeRequest(string queryPath, string getparms)
{
var request = (HttpWebRequest)WebRequest.Create(GetRequestURL(EndPoint, queryPath, getparms));
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
{
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if ((int)response.StatusCode < 200 && (int)response.StatusCode >= 300)
{
throw new MoyaApiException("Request failed", response.StatusCode);
}
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
return responseValue;
}
}
catch (WebException e)
{
var errorResponse = e.Response as HttpWebResponse;
if (errorResponse != null && errorResponse.StatusCode == HttpStatusCode.NotFound)
{
throw new MoyaApiException("Resource not found", HttpStatusCode.NotFound, e);
}
if (e.Status == WebExceptionStatus.ConnectFailure)
{
throw;
}
var responseStream = e.Response.GetResponseStream();
if (responseStream != null)
{
var responseValue = StreamToString(responseStream);
Console.WriteLine("Response was " + responseValue);
throw new WebException(responseValue, e);
}
throw;
}
}
/// <summary>
/// Convert streams from web to string
/// </summary>
/// <param name="responseStream">Webresponse stream</param>
/// <returns>string</returns>
private string StreamToString(Stream responseStream)
{
var reader = new StreamReader(responseStream);
var responseString = reader.ReadToEnd();
responseStream.Close();
reader.Close();
return responseString;
}
}
}