5 using System.Net.Http.Headers;
7 using System.Threading.Tasks;
9 namespace WeatherInformation.Model.Services
11 class CustomHTTPClient
13 async public Task<string> GetWeatherDataAsync(string uri)
15 if (string.IsNullOrEmpty(uri))
17 throw new ArgumentException("Missing argument", "uri");
20 // TODO: it would be nice to use the same HttpClient for the the 2 requests instead of creating
21 // a new one for each connection. :( Not easy with using statement and async :(
22 using(HttpClientHandler handler = new HttpClientHandler
24 // TODO: check if this really works when receiving compressed data.
25 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
27 using (HttpClient client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) })
29 HttpRequestHeaders headers = client.DefaultRequestHeaders;
31 headers.UserAgent.Clear();
32 headers.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("WeatherInformation", "WP8")));
34 headers.AcceptCharset.Clear();
35 headers.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
37 headers.Accept.Clear();
38 headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
40 headers.AcceptEncoding.Clear();
41 headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
42 headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
44 // Bypassing Windows cache
45 string uriWindowsCacheSucks = String.Concat(uri, "&time=", DateTime.UtcNow.Ticks);
47 // TODO: HttpCompletionOption, without it, by default, I am buffering the received data.
48 // in this case it is not a problem but when receiving loads of bytes I do not
49 // think it is a great idea to buffer all of them... :(
50 using (HttpResponseMessage response = await client.GetAsync(uriWindowsCacheSucks).ConfigureAwait(false))
52 response.EnsureSuccessStatusCode();
54 using (HttpContent contentRESULT = response.Content)
56 return await this.ReadResponseAsync(contentRESULT).ConfigureAwait(false);
62 async private Task<string> ReadResponseAsync(HttpContent content)
65 if (content.Headers != null && content.Headers.ContentType != null && content.Headers.ContentType.CharSet != null)
67 encoding = Encoding.GetEncoding(content.Headers.ContentType.CharSet);
71 encoding = Encoding.UTF8;
74 using (Stream stream = await content.ReadAsStreamAsync().ConfigureAwait(false))
75 using (StreamReader streamReader = new StreamReader(stream, encoding))
77 return await streamReader.ReadToEndAsync().ConfigureAwait(false);