forked from tomrus88/WoW-Community-Platform-API
/
ApiRequest.cs
74 lines (66 loc) · 2.17 KB
/
ApiRequest.cs
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
using System;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Caching;
namespace WCPAPI
{
public enum Locale
{
en_US,
es_MX,
en_GB,
fr_FR,
ru_RU,
de_DE,
ko_KR,
zh_TW,
zh_CN,
pt_PT,
pt_BR
}
public class ApiRequest
{
public T Get<T>(string url, DateTime? ifModifiedSince = null) where T : class
{
HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
if (ifModifiedSince.HasValue)
webRequest.IfModifiedSince = ifModifiedSince.Value;
try
{
using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
{
var serializer = new DataContractJsonSerializer(typeof(T));
T result = (T)serializer.ReadObject(webResponse.GetResponseStream());
//DataCache.Add(result.GetHashCode().ToString(), result);
return result;
}
}
catch (WebException web)
{
if (web.Status == WebExceptionStatus.ProtocolError)
{
if (web.Response != null)
{
var resp = web.Response as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.NotFound)
return null;
if (resp.StatusCode == HttpStatusCode.NotModified)
{
return null; // grab from the cache?
//return (T)DataCache.Get(key);
}
var serializer = new DataContractJsonSerializer(typeof(ApiError));
return (T)serializer.ReadObject(resp.GetResponseStream());
}
}
return null;
}
catch
{
return null;
}
}
}
}