My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using System.Threading;
using System.Text.RegularExpressions;
using System.Xml;

namespace Amundsen.Utilities
{
/// <summary>
/// Public Domain 2008-2010 amundsen.com, inc.
/// @author mike amundsen (mamund@yahoo.com)
/// @version 1.0 (2008-07-03)
/// </summary>
public class HttpClient
{
private MemoryStream ms = new MemoryStream();
private bool _UseBinaryStream = false;
public bool UseBinaryStream
{
get { return _UseBinaryStream; }
set { _UseBinaryStream = value; }
}

private WebHeaderCollection _RequestHeaders = new WebHeaderCollection();
public WebHeaderCollection RequestHeaders
{
get { return _RequestHeaders; }
set { _RequestHeaders = value; }
}

private WebHeaderCollection _ResponseHeaders = new WebHeaderCollection();
public WebHeaderCollection ResponseHeaders
{
get { return _ResponseHeaders; }
set { _ResponseHeaders = value; }
}

private CookieContainer _CookieCollection = new CookieContainer();
public CookieContainer CookieCollection
{
get { return _CookieCollection; }
set { _CookieCollection = value; }
}

private HttpStatusCode _ResponseStatusCode = HttpStatusCode.OK;
public HttpStatusCode ResponseStatusCode
{
get { return _ResponseStatusCode; }
set { _ResponseStatusCode = value; }
}

private string _ResponseDescription = string.Empty;
public string ResponseDescription
{
get { return _ResponseDescription; }
set { _ResponseDescription = value; }
}

private DateTime _ResponseLastModified = System.DateTime.MaxValue;
public DateTime ResponseLastModified
{
get { return _ResponseLastModified; }
set { _ResponseLastModified = value; }
}

private NetworkCredential _Credentials = new NetworkCredential();
public NetworkCredential Credentials
{
get { return _Credentials; }
set { _Credentials = value; }
}

private long _ResponseLength;
public long ResponseLength
{
get { return _ResponseLength; }
set { _ResponseLength = value; }
}

private string _UserAgent = string.Empty;
public string UserAgent
{
get { return _UserAgent; }
set { _UserAgent = value; }
}

private bool _PreAuthenticate = true;
public bool PreAuthenticate
{
get { return _PreAuthenticate; }
set { _PreAuthenticate = value; }
}

private string _HttpVersion = "1.1";
public string HttpVersion
{
get { return _HttpVersion; }
set { _HttpVersion = value; }
}

private bool _FollowRedirects = true;
public bool FollowRedirects
{
get { return _FollowRedirects; }
set { _FollowRedirects = value; }
}

private bool _KeepAlive = true;
public bool KeepAlive
{
get { return _KeepAlive; }
set { _KeepAlive = value; }
}

public HttpClient() { }
public HttpClient(NetworkCredential credentials)
{
this.Credentials = credentials;
}
public HttpClient(string user, string password)
{
this.Credentials = new NetworkCredential(user, password);
}
// method that makes the call
public string Execute(string url)
{
return Execute(url, "get", "text/xml", string.Empty, ref ms);
}
public string Execute(string url, string method)
{
return Execute(url, method, "text/xml", string.Empty, ref ms);
}
public string Execute(string url, string method, string contentType)
{
return Execute(url, method, contentType, string.Empty, ref ms);
}
public string Execute(string url, string method, string contentType, string body)
{
return Execute(url, method, contentType, body, ref ms);
}
public string Execute(string url, string method, string contentType, string body, ref MemoryStream ms)
{

HttpWebRequest req = null;
HttpWebResponse resp = null;
string rtnBody = string.Empty;

try
{
// build request object
req = (HttpWebRequest)WebRequest.Create(url);

req.UserAgent = (this.UserAgent.Length != 0 ? this.UserAgent : "amundsen-client/1.0");
req.Method = method.ToUpper(CultureInfo.CurrentCulture);
req.ContentType = contentType;
req.Accept = contentType;
req.ContentLength = body.Length;
req.PreAuthenticate = this.PreAuthenticate;

/* requires full-trust.
* doesn't flow across domains in .net
* also funky in mono 2.0 (object errors)
* use authorization header instead
if (this.Credentials.UserName.Length != 0)
{
req.Credentials = this.Credentials;
}
*/

req.KeepAlive = this.KeepAlive;

// set headers
if (this.RequestHeaders != null)
{
for (int i = 0; i < this.RequestHeaders.Count; i++)
{
// some headers must be set as properties only
string key = this.RequestHeaders.GetKey(i);
string value = this.RequestHeaders[i];
switch (key.ToLower(CultureInfo.CurrentCulture))
{
case "user-agent":
req.UserAgent = value;
break;
case "if-modified-since":
req.IfModifiedSince = DateTime.Parse(value,CultureInfo.CurrentCulture);
break;
case "accept":
req.Accept = value;
break;
default:
req.Headers.Set(key, value);
break;
}
}
}

// set cookies
if (this.CookieCollection != null)
req.CookieContainer = this.CookieCollection;
if (HttpContext.Current != null &&
HttpContext.Current.Request != null &&
HttpContext.Current.Request.Headers != null &&
HttpContext.Current.Request.Headers["cookie"] != null
)
req.CookieContainer.SetCookies(new Uri(url), HttpContext.Current.Request.Headers["cookie"]);

// set body
if (body != null && body.Trim().Length!=0)
{
using (StreamWriter sw = new StreamWriter(req.GetRequestStream()))
{
sw.Write(body);
sw.Close();
}
}

// tweak request
req.ProtocolVersion = new Version(this.HttpVersion);
req.AllowAutoRedirect = this.FollowRedirects;

// now use request obj to populate response obj
resp = (HttpWebResponse)req.GetResponse();

// get response properties
this.ResponseLength = resp.ContentLength;
this.ResponseStatusCode = resp.StatusCode;
this.ResponseDescription = resp.StatusDescription;
this.ResponseLastModified = resp.LastModified;

// get response headers
this.ResponseHeaders = resp.Headers;

// update cookies
this.CookieCollection = new CookieContainer();
foreach (Cookie ck in resp.Cookies)
this.CookieCollection.Add(ck);

// get response body
if (resp.ContentLength != 0)
{
if (this._UseBinaryStream==true)
{
ms = new MemoryStream();
long size = StreamCopy(resp.GetResponseStream(), ms);
}
else
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream(),true))
{
rtnBody = sr.ReadToEnd();
sr.Close();

}
}
}

// clean up
if (resp != null)
resp.Close();

resp = null;
req = null;

// return the results (if any)
return rtnBody;
}
catch (HttpException hex)
{
throw new HttpException(hex.GetHttpCode(), hex.Message);
}
catch (WebException wex)
{
// typical http error
if (wex.Status == WebExceptionStatus.ProtocolError)
{
string msg = string.Empty;
string code = string.Empty;
string xcode = string.Empty;
HttpWebResponse wrsp = (HttpWebResponse)wex.Response;

msg = wrsp.StatusDescription;
code = ((int)wrsp.StatusCode).ToString();

throw new HttpException(Int32.Parse(code), msg);
}
else
{
throw new HttpException(500, wex.Message);
}
}
catch (Exception ex)
{
throw new HttpException(500, ex.Message);
}
}

// handle streaming bytes
protected static long StreamCopy(Stream input, Stream output)
{
byte[] buffer = new byte[64 * 1024];
long length = 0L;

for (; ; )
{
int read = input.Read(buffer, 0, buffer.Length);
if (read > 0)
{
length += (long)read;
output.Write(buffer, 0, read);
}
else
break;
}

return length;
}
}
}

Change log

r127 by mca.amundsen on Jan 11, 2010   Diff
updated for public use
Go to: 
Project members, sign in to write a code review

Older revisions

r126 by m...@amundsen.com on May 25, 2009   Diff
added Amundsen.Utilities project
All revisions of this file

File info

Size: 9189 bytes, 326 lines
Powered by Google Project Hosting