Skip to content

@lars-erik /gist:2365774
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
HttpClient testwrapper
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
Something went wrong with that request. Please try again.