-
Notifications
You must be signed in to change notification settings - Fork 4
/
HttpWebRequestExtensions.cs
70 lines (60 loc) · 1.94 KB
/
HttpWebRequestExtensions.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
using System;
using System.Net;
using System.Threading;
using System.IO;
namespace System.Net
{
public static class HttpWebRequestExtensions
{
public static HttpWebResponse GetResponse(this HttpWebRequest request, bool throwOnError)
{
try
{
return (HttpWebResponse)request.GetResponse(true);
}
catch (WebException we)
{
if ((!throwOnError) && (we.Response != null))
{
return (HttpWebResponse)we.Response;
}
throw;
}
}
#if WINDOWS_PHONE
private const int DefaultRequestTimeout = 5000;
public static HttpWebResponse GetResponse(this HttpWebRequest request)
{
var dataReady = new AutoResetEvent(false);
HttpWebResponse response = null;
var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
{
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
dataReady.Set();
});
request.BeginGetResponse(callback, request);
if (dataReady.WaitOne(DefaultRequestTimeout))
{
return response;
}
return null;
}
public static Stream GetRequestStream(this HttpWebRequest request)
{
var dataReady = new AutoResetEvent(false);
Stream stream = null;
var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
{
stream = (Stream)request.EndGetRequestStream(asynchronousResult);
dataReady.Set();
});
request.BeginGetRequestStream(callback, request);
if (!dataReady.WaitOne(DefaultRequestTimeout))
{
return null;
}
return stream;
}
#endif
}
}