public
Created

HttpClient testwrapper

  • Download Gist
gistfile1.cs
C#
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
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;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.