-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebClientExtensions.cs
198 lines (184 loc) · 7.31 KB
/
WebClientExtensions.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
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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace ReeCode
{
public static class WebClientExtensions
{
/// <summary>
/// Sets the Forwarded header.
/// </summary>
public static WebClient SetForwarded(this WebClient theWebClient, string via)
{
WebClient wc = theWebClient;
// Since HttpRequestHeader.Forwarded is missing...
theWebClient.Headers["Forwarded"] = via;
return wc;
}
/// <summary>
/// Sets the Via header.
/// </summary>
public static WebClient SetVia(this WebClient theWebClient, string via)
{
WebClient wc = theWebClient;
theWebClient.Headers[HttpRequestHeader.Via] = via;
return wc;
}
/// <summary>
/// Sets the Cookie.
/// </summary>
public static WebClient SetCookie(this WebClient theWebClient, string cookie)
{
WebClient wc = theWebClient;
theWebClient.Headers[HttpRequestHeader.Cookie] = cookie;
return wc;
}
/*
public static string GetCookie(this CookieAwareWebClient theWebClient)
{
WebClient wc = theWebClient;
var headers = theWebClient.ResponseHeaders;
var items = Enumerable
.Range(0, headers.Count)
.SelectMany(i => headers.GetValues(i)
.Select(v => Tuple.Create(headers.GetKey(i), v))
);
if (headers.AllKeys.Contains("Set-Cookie") && headers["Set-Cookie"] != "")
{
return headers["Set-Cookie"];
}
else
{
return "";
}
}
*/
/// <summary>
/// Sets the Content Type
/// </summary>
public static WebClient SetContentType(this WebClient theWebClient, string contentType)
{
WebClient wc = theWebClient;
theWebClient.Headers["Content-Type"] = contentType;
return wc;
}
/// <summary>
/// <para>Makes a WebClient GET request, and returns the result as a string.</para>
/// <para>Similar to DownloadString, but with better functionality :)</para>
/// </summary>
public static string Get(this WebClient theWebClient, string URL, Dictionary<string, string> urlParams = null)
{
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
if (urlParams != null && urlParams.Any())
{
URL += "?";
foreach (var item in urlParams)
{
// HTML Entities?
URL += item.Key + "=" + item.Value + "&";
}
URL = URL.Trim('&');
}
try
{
string response = theWebClient.DownloadString(URL);
return response;
}
catch (WebException wex)
{
if (wex.Response == null)
{
Console.WriteLine("Error in Get - " + wex.Message);
return "";
}
if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound || ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.Unauthorized)
{
StreamReader sr1 = new StreamReader(wex.Response.GetResponseStream());
string theLine = sr1.ReadToEnd();
return theLine;
}
else
{
Console.WriteLine("Error in Get - " + wex.Message);
return "";
}
}
}
/// <summary>
/// Makes a WebClient POST request, and returns the result as a string.
/// </summary>
public static string Post(this WebClient theWebClient, string URL, Dictionary<string, string> postValues, bool isJSON = false)
{
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
NameValueCollection postCollection = new NameValueCollection();
foreach (var item in postValues)
{
postCollection.Add(item.Key, item.Value);
}
try
{
if (isJSON)
{
// As far as I know, you have to have this for POSTing JSON Data - Might be wrong?
theWebClient.SetContentType("application/json");
// TODO: Find a nice way to do Complex JSon Objects - Not just as a class....
// Instead of just { "name1" : "value1", "name2" : "value2" }
// Do { "name1" : { "subName1" : "subValue1", "subName2" : "subValue2" }, "name2" : "value2" }
var jsonData = postCollection.AllKeys.ToDictionary(x => x, x => postCollection[x]);
// using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(jsonData);
string response = theWebClient.UploadString(URL, json);
return response;
}
else
{
byte[] responseBytes = theWebClient.UploadValues(URL, "POST", postCollection);
string responseString = Encoding.UTF8.GetString(responseBytes);
return responseString;
}
}
catch (WebException wex)
{
if (wex.Response == null)
{
Console.WriteLine("Error in Post - " + wex.Message);
return "";
}
if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound || ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.Unauthorized)
{
StreamReader sr1 = new StreamReader(wex.Response.GetResponseStream());
string theLine = sr1.ReadToEnd();
return theLine;
}
else
{
Console.WriteLine("Error in Post - " + wex.Message);
return "";
}
}
}
}
// For those times when you need persistence (PHPSESSID)
public class CookieAwareWebClient : WebClient
{
// An aptly named container to store the Cookie
public CookieContainer CookieContainer { get; private set; }
public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
// Grabs the base request being made
var request = (HttpWebRequest)base.GetWebRequest(address);
// Adds the existing cookie container to the Request
request.CookieContainer = CookieContainer;
return request;
}
}
}