Switched from WebClient to HTTPClient

This commit is contained in:
Jonas Dellinger 2017-05-31 17:25:56 +02:00
parent 8acea4f36e
commit 25a21fd342
6 changed files with 191 additions and 227 deletions

View File

@ -38,7 +38,7 @@ namespace SpotifyAPI.Example
} }
authButton.Enabled = false; authButton.Enabled = false;
_profile = _spotify.GetPrivateProfile(); _profile = await _spotify.GetPrivateProfileAsync();
_savedTracks = GetSavedTracks(); _savedTracks = GetSavedTracks();
savedTracksCountLabel.Text = _savedTracks.Count.ToString(); savedTracksCountLabel.Text = _savedTracks.Count.ToString();

View File

@ -4,6 +4,7 @@ using NUnit.Framework;
using SpotifyAPI.Web; using SpotifyAPI.Web;
using SpotifyAPI.Web.Models; using SpotifyAPI.Web.Models;
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@ -50,23 +51,29 @@ namespace SpotifyAPI.Tests
public void ShouldGetPrivateProfile_WithAuth() public void ShouldGetPrivateProfile_WithAuth()
{ {
PrivateProfile profile = GetFixture<PrivateProfile>("private-user.json"); PrivateProfile profile = GetFixture<PrivateProfile>("private-user.json");
_mock.Setup(client => client.DownloadJson<PrivateProfile>(It.IsAny<string>())) _mock.Setup(client => client.DownloadJson<PrivateProfile>(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>()))
.Returns(new Tuple<ResponseInfo, PrivateProfile>(ResponseInfo.Empty, profile)); .Returns(new Tuple<ResponseInfo, PrivateProfile>(ResponseInfo.Empty, profile));
_spotify.UseAuth = true; _spotify.UseAuth = true;
Assert.AreEqual(profile, _spotify.GetPrivateProfile()); Assert.AreEqual(profile, _spotify.GetPrivateProfile());
_mock.Verify(client => client.DownloadJson<PrivateProfile>(It.Is<string>(str => ContainsValues(str, "/me"))), Times.Exactly(1)); _mock.Verify(client => client.DownloadJson<PrivateProfile>(
It.Is<string>(str => ContainsValues(str, "/me")),
It.IsNotNull<Dictionary<string, string>>()), Times.Exactly(1));
} }
[Test] [Test]
public void ShouldGetPublicProfile() public void ShouldGetPublicProfile()
{ {
PublicProfile profile = GetFixture<PublicProfile>("public-user.json"); PublicProfile profile = GetFixture<PublicProfile>("public-user.json");
_mock.Setup(client => client.DownloadJson<PublicProfile>(It.IsAny<string>())) _mock.Setup(client => client.DownloadJson<PublicProfile>(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>()))
.Returns(new Tuple<ResponseInfo, PublicProfile>(ResponseInfo.Empty, profile)); .Returns(new Tuple<ResponseInfo, PublicProfile>(ResponseInfo.Empty, profile));
_spotify.UseAuth = false;
Assert.AreEqual(profile, _spotify.GetPublicProfile("wizzler")); Assert.AreEqual(profile, _spotify.GetPublicProfile("wizzler"));
_mock.Verify(client => client.DownloadJson<PublicProfile>(It.Is<string>(str => ContainsValues(str, "/users/wizzler"))), Times.Exactly(1)); _mock.Verify(client => client.DownloadJson<PublicProfile>(
It.Is<string>(str => ContainsValues(str, "/users/wizzler")),
It.Is<Dictionary<string, string>>(headers => headers.Count == 0)), Times.Exactly(1));
} }
//Will add more tests once I decided if this is worth the effort (propably not?) //Will add more tests once I decided if this is worth the effort (propably not?)

View File

@ -45,6 +45,7 @@
<Reference Include="System.ComponentModel.DataAnnotations" /> <Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Web" /> <Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />

View File

@ -1,6 +1,7 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using SpotifyAPI.Web.Models; using SpotifyAPI.Web.Models;
@ -15,28 +16,28 @@ namespace SpotifyAPI.Web
/// </summary> /// </summary>
/// <param name="url">An URL</param> /// <param name="url">An URL</param>
/// <returns></returns> /// <returns></returns>
Tuple<ResponseInfo, string> Download(string url); Tuple<ResponseInfo, string> Download(string url, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Downloads data async from an URL and returns it /// Downloads data async from an URL and returns it
/// </summary> /// </summary>
/// <param name="url"></param> /// <param name="url"></param>
/// <returns></returns> /// <returns></returns>
Task<Tuple<ResponseInfo, string>> DownloadAsync(string url); Task<Tuple<ResponseInfo, string>> DownloadAsync(string url, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Downloads data from an URL and returns it /// Downloads data from an URL and returns it
/// </summary> /// </summary>
/// <param name="url">An URL</param> /// <param name="url">An URL</param>
/// <returns></returns> /// <returns></returns>
Tuple<ResponseInfo, byte[]> DownloadRaw(string url); Tuple<ResponseInfo, byte[]> DownloadRaw(string url, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Downloads data async from an URL and returns it /// Downloads data async from an URL and returns it
/// </summary> /// </summary>
/// <param name="url"></param> /// <param name="url"></param>
/// <returns></returns> /// <returns></returns>
Task<Tuple<ResponseInfo, byte[]>> DownloadRawAsync(string url); Task<Tuple<ResponseInfo, byte[]>> DownloadRawAsync(string url, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Downloads data from an URL and converts it to an object /// Downloads data from an URL and converts it to an object
@ -44,7 +45,7 @@ namespace SpotifyAPI.Web
/// <typeparam name="T">The Type which the object gets converted to</typeparam> /// <typeparam name="T">The Type which the object gets converted to</typeparam>
/// <param name="url">An URL</param> /// <param name="url">An URL</param>
/// <returns></returns> /// <returns></returns>
Tuple<ResponseInfo, T> DownloadJson<T>(string url); Tuple<ResponseInfo, T> DownloadJson<T>(string url, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Downloads data async from an URL and converts it to an object /// Downloads data async from an URL and converts it to an object
@ -52,7 +53,7 @@ namespace SpotifyAPI.Web
/// <typeparam name="T">The Type which the object gets converted to</typeparam> /// <typeparam name="T">The Type which the object gets converted to</typeparam>
/// <param name="url">An URL</param> /// <param name="url">An URL</param>
/// <returns></returns> /// <returns></returns>
Task<Tuple<ResponseInfo, T>> DownloadJsonAsync<T>(string url); Task<Tuple<ResponseInfo, T>> DownloadJsonAsync<T>(string url, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Uploads data from an URL and returns the response /// Uploads data from an URL and returns the response
@ -61,7 +62,7 @@ namespace SpotifyAPI.Web
/// <param name="body">The Body-Data (most likely a JSON String)</param> /// <param name="body">The Body-Data (most likely a JSON String)</param>
/// <param name="method">The Upload-method (POST,DELETE,PUT)</param> /// <param name="method">The Upload-method (POST,DELETE,PUT)</param>
/// <returns></returns> /// <returns></returns>
Tuple<ResponseInfo, string> Upload(string url, string body, string method); Tuple<ResponseInfo, string> Upload(string url, string body, string method, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Uploads data async from an URL and returns the response /// Uploads data async from an URL and returns the response
@ -70,7 +71,7 @@ namespace SpotifyAPI.Web
/// <param name="body">The Body-Data (most likely a JSON String)</param> /// <param name="body">The Body-Data (most likely a JSON String)</param>
/// <param name="method">The Upload-method (POST,DELETE,PUT)</param> /// <param name="method">The Upload-method (POST,DELETE,PUT)</param>
/// <returns></returns> /// <returns></returns>
Task<Tuple<ResponseInfo, string>> UploadAsync(string url, string body, string method); Task<Tuple<ResponseInfo, string>> UploadAsync(string url, string body, string method, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Uploads data from an URL and returns the response /// Uploads data from an URL and returns the response
@ -79,7 +80,7 @@ namespace SpotifyAPI.Web
/// <param name="body">The Body-Data (most likely a JSON String)</param> /// <param name="body">The Body-Data (most likely a JSON String)</param>
/// <param name="method">The Upload-method (POST,DELETE,PUT)</param> /// <param name="method">The Upload-method (POST,DELETE,PUT)</param>
/// <returns></returns> /// <returns></returns>
Tuple<ResponseInfo, byte[]> UploadRaw(string url, string body, string method); Tuple<ResponseInfo, byte[]> UploadRaw(string url, string body, string method, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Uploads data async from an URL and returns the response /// Uploads data async from an URL and returns the response
@ -88,7 +89,7 @@ namespace SpotifyAPI.Web
/// <param name="body">The Body-Data (most likely a JSON String)</param> /// <param name="body">The Body-Data (most likely a JSON String)</param>
/// <param name="method">The Upload-method (POST,DELETE,PUT)</param> /// <param name="method">The Upload-method (POST,DELETE,PUT)</param>
/// <returns></returns> /// <returns></returns>
Task<Tuple<ResponseInfo, byte[]>> UploadRawAsync(string url, string body, string method); Task<Tuple<ResponseInfo, byte[]>> UploadRawAsync(string url, string body, string method, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Uploads data from an URL and converts the response to an object /// Uploads data from an URL and converts the response to an object
@ -98,7 +99,7 @@ namespace SpotifyAPI.Web
/// <param name="body">The Body-Data (most likely a JSON String)</param> /// <param name="body">The Body-Data (most likely a JSON String)</param>
/// <param name="method">The Upload-method (POST,DELETE,PUT)</param> /// <param name="method">The Upload-method (POST,DELETE,PUT)</param>
/// <returns></returns> /// <returns></returns>
Tuple<ResponseInfo, T> UploadJson<T>(string url, string body, string method); Tuple<ResponseInfo, T> UploadJson<T>(string url, string body, string method, Dictionary<string, string> headers = null);
/// <summary> /// <summary>
/// Uploads data async from an URL and converts the response to an object /// Uploads data async from an URL and converts the response to an object
@ -108,25 +109,6 @@ namespace SpotifyAPI.Web
/// <param name="body">The Body-Data (most likely a JSON String)</param> /// <param name="body">The Body-Data (most likely a JSON String)</param>
/// <param name="method">The Upload-method (POST,DELETE,PUT)</param> /// <param name="method">The Upload-method (POST,DELETE,PUT)</param>
/// <returns></returns> /// <returns></returns>
Task<Tuple<ResponseInfo, T>> UploadJsonAsync<T>(string url, string body, string method); Task<Tuple<ResponseInfo, T>> UploadJsonAsync<T>(string url, string body, string method, Dictionary<string, string> headers = null);
/// <summary>
/// Sets a specific Header
/// </summary>
/// <param name="header">Header name</param>
/// <param name="value">Header value</param>
void SetHeader(string header, string value);
/// <summary>
/// Removes a specific Header
/// </summary>
/// <param name="header">Header name</param>
void RemoveHeader(string header);
/// <summary>
/// Gets all current Headers
/// </summary>
/// <returns>A collection of Header KeyValue Pairs</returns>
List<KeyValuePair<string, string>> GetHeaders();
} }
} }

View File

@ -2115,11 +2115,14 @@ namespace SpotifyAPI.Web
Tuple<ResponseInfo, T> response = null; Tuple<ResponseInfo, T> response = null;
do do
{ {
WebClient.SetHeader("Authorization", TokenType + " " + AccessToken); Dictionary<string, string> headers = new Dictionary<string, string>
WebClient.SetHeader("Content-Type", "application/json"); {
{ "Authorization", TokenType + " " + AccessToken},
{ "Content-Type", "application/json" }
};
if (response != null) { Thread.Sleep(RetryAfter); } if (response != null) { Thread.Sleep(RetryAfter); }
response = WebClient.UploadJson<T>(url, uploadData, method); response = WebClient.UploadJson<T>(url, uploadData, method, headers);
response.Item2.AddResponseInfo(response.Item1); response.Item2.AddResponseInfo(response.Item1);
lastError = response.Item2.Error; lastError = response.Item2.Error;
@ -2142,11 +2145,14 @@ namespace SpotifyAPI.Web
Tuple<ResponseInfo, T> response = null; Tuple<ResponseInfo, T> response = null;
do do
{ {
WebClient.SetHeader("Authorization", TokenType + " " + AccessToken); Dictionary<string, string> headers = new Dictionary<string, string>
WebClient.SetHeader("Content-Type", "application/json"); {
{ "Authorization", TokenType + " " + AccessToken},
{ "Content-Type", "application/json" }
};
if (response != null) { await Task.Delay(RetryAfter).ConfigureAwait(false); } if (response != null) { await Task.Delay(RetryAfter).ConfigureAwait(false); }
response = await WebClient.UploadJsonAsync<T>(url, uploadData, method).ConfigureAwait(false); response = await WebClient.UploadJsonAsync<T>(url, uploadData, method, headers).ConfigureAwait(false);
response.Item2.AddResponseInfo(response.Item1); response.Item2.AddResponseInfo(response.Item1);
lastError = response.Item2.Error; lastError = response.Item2.Error;
@ -2204,20 +2210,18 @@ namespace SpotifyAPI.Web
private Tuple<ResponseInfo, T> DownloadDataAlt<T>(string url) private Tuple<ResponseInfo, T> DownloadDataAlt<T>(string url)
{ {
Dictionary<string, string> headers = new Dictionary<string, string>();
if (UseAuth) if (UseAuth)
WebClient.SetHeader("Authorization", TokenType + " " + AccessToken); headers.Add("Authorization", TokenType + " " + AccessToken);
else return WebClient.DownloadJson<T>(url, headers);
WebClient.RemoveHeader("Authorization");
return WebClient.DownloadJson<T>(url);
} }
private Task<Tuple<ResponseInfo, T>> DownloadDataAltAsync<T>(string url) private Task<Tuple<ResponseInfo, T>> DownloadDataAltAsync<T>(string url)
{ {
Dictionary<string, string> headers = new Dictionary<string, string>();
if (UseAuth) if (UseAuth)
WebClient.SetHeader("Authorization", TokenType + " " + AccessToken); headers.Add("Authorization", TokenType + " " + AccessToken);
else return WebClient.DownloadJsonAsync<T>(url, headers);
WebClient.RemoveHeader("Authorization");
return WebClient.DownloadJsonAsync<T>(url);
} }
#endregion Util #endregion Util

View File

@ -4,6 +4,8 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using SpotifyAPI.Web.Models; using SpotifyAPI.Web.Models;
@ -14,198 +16,166 @@ namespace SpotifyAPI.Web
{ {
public JsonSerializerSettings JsonSettings { get; set; } public JsonSerializerSettings JsonSettings { get; set; }
private readonly WebClient _webClient;
private readonly Encoding _encoding = Encoding.UTF8; private readonly Encoding _encoding = Encoding.UTF8;
public SpotifyWebClient() public Tuple<ResponseInfo, string> Download(string url, Dictionary<string, string> headers = null)
{ {
_webClient = new WebClient() Tuple<ResponseInfo, byte[]> raw = DownloadRaw(url, headers);
return new Tuple<ResponseInfo, string>(raw.Item1, raw.Item2.Length > 0 ? _encoding.GetString(raw.Item2) : "{}");
}
public async Task<Tuple<ResponseInfo, string>> DownloadAsync(string url, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, byte[]> raw = await DownloadRawAsync(url, headers).ConfigureAwait(false);
return new Tuple<ResponseInfo, string>(raw.Item1, raw.Item2.Length > 0 ? _encoding.GetString(raw.Item2) : "{}");
}
public Tuple<ResponseInfo, byte[]> DownloadRaw(string url, Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{ {
Proxy = null, if (headers != null)
Encoding = _encoding {
}; foreach (KeyValuePair<string, string> headerPair in headers)
{
client.DefaultRequestHeaders.Add(headerPair.Key, headerPair.Value);
}
}
using (HttpResponseMessage response = Task.Run(() => client.GetAsync(url)).Result)
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo()
{
Headers = ConvertHeaders(response.Headers)
}, Task.Run(() => response.Content.ReadAsByteArrayAsync()).Result);
}
}
}
public async Task<Tuple<ResponseInfo, byte[]>> DownloadRawAsync(string url, Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> headerPair in headers)
{
client.DefaultRequestHeaders.Add(headerPair.Key, headerPair.Value);
}
}
using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false))
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo()
{
Headers = ConvertHeaders(response.Headers)
}, await response.Content.ReadAsByteArrayAsync());
}
}
}
public Tuple<ResponseInfo, T> DownloadJson<T>(string url, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, string> response = Download(url, headers);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public async Task<Tuple<ResponseInfo, T>> DownloadJsonAsync<T>(string url, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, string> response = await DownloadAsync(url, headers).ConfigureAwait(false);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public Tuple<ResponseInfo, string> Upload(string url, string body, string method, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, byte[]> data = UploadRaw(url, body, method, headers);
return new Tuple<ResponseInfo, string>(data.Item1, data.Item2.Length > 0 ? _encoding.GetString(data.Item2) : "{}");
}
public async Task<Tuple<ResponseInfo, string>> UploadAsync(string url, string body, string method, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, byte[]> data = await UploadRawAsync(url, body, method, headers).ConfigureAwait(false);
return new Tuple<ResponseInfo, string>(data.Item1, data.Item2.Length > 0 ? _encoding.GetString(data.Item2) : "{}");
}
public Tuple<ResponseInfo, byte[]> UploadRaw(string url, string body, string method, Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> headerPair in headers)
{
client.DefaultRequestHeaders.Add(headerPair.Key, headerPair.Value);
}
}
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url)
{
Content = new StringContent(body, _encoding)
};
using (HttpResponseMessage response = Task.Run(() => client.SendAsync(message)).Result)
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{
Headers = ConvertHeaders(response.Headers)
}, Task.Run(() => response.Content.ReadAsByteArrayAsync()).Result);
}
}
}
public async Task<Tuple<ResponseInfo, byte[]>> UploadRawAsync(string url, string body, string method, Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> headerPair in headers)
{
client.DefaultRequestHeaders.Add(headerPair.Key, headerPair.Value);
}
}
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url)
{
Content = new StringContent(body, _encoding)
};
using (HttpResponseMessage response = await client.SendAsync(message))
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{
Headers = ConvertHeaders(response.Headers)
}, await response.Content.ReadAsByteArrayAsync());
}
}
}
public Tuple<ResponseInfo, T> UploadJson<T>(string url, string body, string method, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, string> response = Upload(url, body, method, headers);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public async Task<Tuple<ResponseInfo, T>> UploadJsonAsync<T>(string url, string body, string method, Dictionary<string, string> headers = null)
{
Tuple<ResponseInfo, string> response = await UploadAsync(url, body, method, headers).ConfigureAwait(false);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
} }
public void Dispose() public void Dispose()
{ {
_webClient.Dispose(); GC.SuppressFinalize(this);
} }
public Tuple<ResponseInfo, string> Download(string url) private static WebHeaderCollection ConvertHeaders(HttpResponseHeaders headers)
{ {
Tuple<ResponseInfo, string> response; WebHeaderCollection newHeaders = new WebHeaderCollection();
try foreach (KeyValuePair<string, IEnumerable<string>> headerPair in headers)
{ {
Tuple<ResponseInfo, byte[]> raw = DownloadRaw(url); foreach (string headerValue in headerPair.Value)
response = new Tuple<ResponseInfo, string>(raw.Item1, raw.Item2.Length > 0 ? _encoding.GetString(raw.Item2) : "{}");
}
catch (WebException e)
{
using (StreamReader reader = new StreamReader(e.Response.GetResponseStream()))
{ {
response = new Tuple<ResponseInfo, string>(new ResponseInfo newHeaders.Add(headerPair.Key, headerValue);
{
Headers = _webClient.ResponseHeaders
}, reader.ReadToEnd());
} }
} }
return response; return newHeaders;
}
public async Task<Tuple<ResponseInfo, string>> DownloadAsync(string url)
{
Tuple<ResponseInfo, string> response;
try
{
Tuple<ResponseInfo, byte[]> raw = await DownloadRawAsync(url).ConfigureAwait(false);
response = new Tuple<ResponseInfo, string>(raw.Item1, raw.Item2.Length > 0 ? _encoding.GetString(raw.Item2) : "{}");
}
catch (WebException e)
{
using (StreamReader reader = new StreamReader(e.Response.GetResponseStream()))
{
response = new Tuple<ResponseInfo, string>(new ResponseInfo
{
Headers = _webClient.ResponseHeaders
}, reader.ReadToEnd());
}
}
return response;
}
public Tuple<ResponseInfo, byte[]> DownloadRaw(string url)
{
byte[] data = _webClient.DownloadData(url);
ResponseInfo info = new ResponseInfo()
{
Headers = _webClient.ResponseHeaders
};
return new Tuple<ResponseInfo, byte[]>(info, data);
}
public async Task<Tuple<ResponseInfo, byte[]>> DownloadRawAsync(string url)
{
using (WebClient webClient = new WebClient())
{
webClient.Proxy = null;
webClient.Encoding = _encoding;
webClient.Headers = _webClient.Headers;
byte[] data = await _webClient.DownloadDataTaskAsync(url).ConfigureAwait(false);
ResponseInfo info = new ResponseInfo()
{
Headers = webClient.ResponseHeaders
};
return new Tuple<ResponseInfo, byte[]>(info, data);
}
}
public Tuple<ResponseInfo, T> DownloadJson<T>(string url)
{
Tuple<ResponseInfo, string> response = Download(url);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public async Task<Tuple<ResponseInfo, T>> DownloadJsonAsync<T>(string url)
{
Tuple<ResponseInfo, string> response = await DownloadAsync(url).ConfigureAwait(false);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public Tuple<ResponseInfo, string> Upload(string url, string body, string method)
{
Tuple<ResponseInfo, string> response;
try
{
Tuple<ResponseInfo, byte[]> data = UploadRaw(url, body, method);
response = new Tuple<ResponseInfo, string>(data.Item1, data.Item2.Length > 0 ? _encoding.GetString(data.Item2) : "{}");
}
catch (WebException e)
{
using (StreamReader reader = new StreamReader(e.Response.GetResponseStream()))
{
response = new Tuple<ResponseInfo, string>(new ResponseInfo
{
Headers = _webClient.ResponseHeaders
}, reader.ReadToEnd());
}
}
return response;
}
public async Task<Tuple<ResponseInfo, string>> UploadAsync(string url, string body, string method)
{
Tuple<ResponseInfo, string> response;
try
{
Tuple<ResponseInfo, byte[]> data = await UploadRawAsync(url, body, method).ConfigureAwait(false);
response = new Tuple<ResponseInfo, string>(data.Item1, data.Item2.Length > 0 ? _encoding.GetString(data.Item2) : "{}");
}
catch (WebException e)
{
using (StreamReader reader = new StreamReader(e.Response.GetResponseStream()))
{
response = new Tuple<ResponseInfo, string>(new ResponseInfo
{
Headers = _webClient.ResponseHeaders
}, reader.ReadToEnd());
}
}
return response;
}
public Tuple<ResponseInfo, byte[]> UploadRaw(string url, string body, string method)
{
byte[] data = _webClient.UploadData(url, method, _encoding.GetBytes(body));
ResponseInfo info = new ResponseInfo
{
Headers = _webClient.ResponseHeaders
};
return new Tuple<ResponseInfo, byte[]>(info, data);
}
public async Task<Tuple<ResponseInfo, byte[]>> UploadRawAsync(string url, string body, string method)
{
using (WebClient webClient = new WebClient())
{
webClient.Proxy = null;
webClient.Encoding = _encoding;
webClient.Headers = _webClient.Headers;
byte[] data = await _webClient.UploadDataTaskAsync(url, method, _encoding.GetBytes(body)).ConfigureAwait(false);
ResponseInfo info = new ResponseInfo
{
Headers = _webClient.ResponseHeaders
};
return new Tuple<ResponseInfo, byte[]>(info, data);
}
}
public Tuple<ResponseInfo, T> UploadJson<T>(string url, string body, string method)
{
Tuple<ResponseInfo, string> response = Upload(url, body, method);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public async Task<Tuple<ResponseInfo, T>> UploadJsonAsync<T>(string url, string body, string method)
{
Tuple<ResponseInfo, string> response = await UploadAsync(url, body, method).ConfigureAwait(false);
return new Tuple<ResponseInfo, T>(response.Item1, JsonConvert.DeserializeObject<T>(response.Item2, JsonSettings));
}
public void SetHeader(string header, string value)
{
_webClient.Headers[header] = value;
}
public void RemoveHeader(string header)
{
if (_webClient.Headers[header] != null)
_webClient.Headers.Remove(header);
}
public List<KeyValuePair<string, string>> GetHeaders()
{
return _webClient.Headers.AllKeys.Select(header => new KeyValuePair<string, string>(header, _webClient.Headers[header])).ToList();
} }
} }
} }