/
Proxy.cs
112 lines (102 loc) · 3.53 KB
/
Proxy.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
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
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SharpGIS.ZLib;
namespace Fotoideen.Helper
{
public class Proxy
{
private bool _enableGZip = false;
public void LoadData(bool enableGzip = false)
{
var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(Constants.DataUrl, UriKind.Absolute));
if (enableGzip)
{
webRequest.Headers["Accept-Encoding"] = "gzip";
}
webRequest.BeginGetResponse(FinishedLoadData, webRequest);
}
private void FinishedLoadData(IAsyncResult asyncRsult)
{
var webRequest = asyncRsult.AsyncState as HttpWebRequest;
try
{
var webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncRsult);
var statusCode = webResponse.StatusCode;
string response = string.Empty;
using (var responseStream = webResponse.GetResponseStream())
{
if (webResponse.Headers["Content-Encoding"] == "gzip")
{
response = UnzipResponse(responseStream);
}
else
{
using (var sr = new StreamReader(responseStream))
{
response = sr.ReadToEnd();
}
}
}
var normalizedResponse = JsonNormalize.DoNormalize(response);
InvokeProxyEvent(new ProxyEventArgs(normalizedResponse, statusCode));
webResponse.Close();
}
catch (WebException ex)
{
var webResponse = (HttpWebResponse)ex.Response;
var statusCode = webResponse.StatusCode;
InvokeProxyEvent(new ProxyEventArgs(string.Empty, statusCode));
webResponse.Close();
}
catch (Exception ex)
{
InvokeProxyEvent(new ProxyEventArgs(string.Empty, HttpStatusCode.Unused));
}
finally
{
webRequest.Abort();
}
}
private string UnzipResponse(Stream input)
{
var sb = new StringBuilder();
using (var zippedStream = new GZipStream(input))
{
using (var reader = new StreamReader(zippedStream))
{
while (!reader.EndOfStream)
{
sb.AppendLine(reader.ReadLine());
}
}
}
return sb.ToString();
}
public event EventHandler ProxyEvent;
private void InvokeProxyEvent(ProxyEventArgs e)
{
EventHandler handler = ProxyEvent;
if (handler != null) handler(this, e);
}
}
public class ProxyEventArgs : EventArgs
{
public string Response { get; set; }
public HttpStatusCode Code { get; set; }
public ProxyEventArgs(string response, HttpStatusCode code)
{
Response = response;
Code = code;
}
}
}