-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncWebRequest.cs
107 lines (94 loc) · 2.56 KB
/
AsyncWebRequest.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
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using Cyclestreets.Resources;
using Cyclestreets.Utils;
namespace Cyclestreets
{
public class AsyncWebRequest
{
private string uri;
private enum EState
{
NOT_STARTED,
STARTED,
COMPLETE,
}
private EState requestState;
private Action<byte[]> OnComplete;
HttpWebRequest request = null;
public AsyncWebRequest(String uri, Action<byte[]> OnComplete)
{
this.uri = uri;
this.OnComplete = OnComplete;
requestState = EState.NOT_STARTED;
}
public async void Start()
{
requestState = EState.STARTED;
byte[] taskData = await Task.Run(() => GetURLContentsAsync(this.uri));
requestState = EState.COMPLETE;
this.OnComplete(taskData);
}
public bool isComplete()
{
return requestState == EState.COMPLETE;
}
public Task<byte[]> GetURLContentsAsync(string url)
{
request = (HttpWebRequest)WebRequest.Create( url );
try
{
Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>( request.BeginGetResponse, request.EndGetResponse, null );
return task.ContinueWith( t =>
{
if( t.IsFaulted )
{
//handle error
//Exception firstException = t.Exception.InnerExceptions.First();
Util.networkFailure();
return null;
}
else
{
return ReadStreamFromResponse( t.Result );
}
} );
//return task.ContinueWith( t => ReadStreamFromResponse( t.Result ) );
}
catch (System.Exception ex)
{
MessageBox.Show( AppResources.GetDataError+url );
FlurryWP8SDK.Api.LogError(AppResources.GetDataError + url, ex);
return null;
}
}
private static byte[] ReadStreamFromResponse( WebResponse response )
{
try
{
using( var responseStream = response.GetResponseStream() )
{
var content = new MemoryStream();
responseStream.CopyTo( content );
return content.ToArray();
}
}
catch( System.Exception ex )
{
FlurryWP8SDK.Api.LogError(@"Failed to read response stream", ex);
return null;
}
}
internal void Stop()
{
if( request != null )
{
request.Abort();
request = null;
}
}
}
}