× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS
Giuseppe Russo
Nov 28, 2014
<pre><code>class Program { static void Main(string[] args) { Task.Factory.StartNew(async () =&gt; { var helper = new WebHelper(); var response = await helper.PostAsync&lt;IpRequest, IpResponse&gt;("http://ip.jsontest.com/", new Request&lt;IpRequest&gt;(new IpRequest("10.1.1.1"))); Console.WriteLine(response); }); Console.ReadKey(true); } }</code></pre><pre><code class="language-cs">public sealed class IpRequest { public string Ip { get; private set; } public IpRequest(string ip) { Ip = ip; } }</code></pre><pre><code class="language-cs">public sealed class IpResponse { public string Ip { get; private set; } public IpResponse(string ip) { Ip = ip; } }</code></pre><pre><code class="language-cs"> public class WebHelper { public async Task&lt;TResponse&gt; PostAsync&lt;TRequest, TResponse&gt;(string url, Request&lt;TRequest&gt; jsonRequest) where TResponse : class { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; var buffer = Encoding.UTF8.GetBytes(jsonRequest.Json); request.ContentLength = buffer.Length; using (var stream = await request.GetRequestStreamAsync()) { await stream.WriteAsync(buffer, 0, buffer.Length); stream.Close(); } using (var response = await request.GetResponseAsync()) { var stream = response.GetResponseStream(); if (stream == null) return default(TResponse); var reader = new StreamReader(stream); return JsonConvert.DeserializeObject&lt;TResponse&gt;(await reader.ReadToEndAsync()); } } public TResponse Post&lt;TRequest, TResponse&gt;(string url, Request&lt;TRequest&gt; jsonRequest) where TResponse : class { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; var buffer = Encoding.UTF8.GetBytes(jsonRequest.Json); request.ContentLength = buffer.Length; using (var stream = request.GetRequestStream()) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } using (var response = request.GetResponse()) { var stream = response.GetResponseStream(); if (stream == null) return default(TResponse); var reader = new StreamReader(stream); return JsonConvert.DeserializeObject&lt;TResponse&gt;(reader.ReadToEnd()); } } }</code></pre><p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus