Created
April 12, 2012 09:16
-
-
Save lars-erik/2365774 to your computer and use it in GitHub Desktop.
HttpClient testwrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Net; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json; | |
namespace AHttpClientTestWrapper | |
{ | |
public class HttpClientWrapper | |
{ | |
private readonly HttpClient client = new HttpClient(); | |
private readonly string url; | |
private TimeSpan timeout = TimeSpan.FromSeconds(15); | |
public HttpClientWrapper(string url) | |
{ | |
client = new HttpClient(); | |
this.url = url; | |
} | |
public TimeSpan Timeout | |
{ | |
get { return timeout; } | |
set { timeout = value; } | |
} | |
public TResult Request<TResult>(object request) | |
where TResult : class, new() | |
{ | |
return EndRequest<TResult>(BeginRequest(request)); | |
} | |
public Task<HttpResponseMessage> BeginRequest(object request) | |
{ | |
var json = JsonConvert.SerializeObject(request); | |
var postTask = client.PostAsync(url, new JsonRequest(json)); | |
return postTask; | |
} | |
public T EndRequest<T>(Task<HttpResponseMessage> task) | |
where T : class, new() | |
{ | |
Task<HttpResponseMessage> response = null; | |
task.ContinueWith(r => response = r).Wait(timeout); | |
return ParseResult<T>(response.Result); | |
} | |
private T ParseResult<T>(HttpResponseMessage response) | |
where T : class, new() | |
{ | |
var result = new T(); | |
response.EnsureSuccessStatusCode(); | |
response.Content | |
.ReadAsStringAsync() | |
.ContinueWith(st => Populate(st, result)) | |
.Wait(timeout); | |
return result; | |
} | |
private static void Populate<T>(Task<string> st, T result) where T : class, new() | |
{ | |
JsonConvert.PopulateObject(st.Result, result); | |
} | |
} | |
public class JsonRequest : HttpContent | |
{ | |
private readonly string json; | |
public JsonRequest(string json) | |
{ | |
this.json = json; | |
} | |
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) | |
{ | |
return Task.Factory.StartNew(WriteToStream, stream); | |
} | |
private void WriteToStream(object o) | |
{ | |
var writer = new StreamWriter(((Stream) o)); | |
writer.Write(json); | |
writer.Flush(); | |
} | |
protected override bool TryComputeLength(out long length) | |
{ | |
length = json.Length; | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment