Guest User

Untitled

a guest
Jul 19th, 2014
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Http;
  4. using System.Threading.Tasks;
  5.  
  6. namespace MonoCSharpBug
  7. {
  8.     class MainClass
  9.     {
  10.         private static readonly HttpClient _httpClient = new HttpClient
  11.         {
  12.             BaseAddress = new Uri("http://ip.jsontest.com/"),
  13.         };
  14.  
  15.         private static async Task<TResponse> SendAsync<TResponse>(HttpMethod httpMethod)
  16.         {
  17.             var requestUri = "/";
  18.  
  19.             using (var httpRequestMessage = new HttpRequestMessage(httpMethod, requestUri))
  20.             {
  21.                 var httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage);
  22.                 return await ReadResponseAsync<TResponse>(httpResponseMessage);
  23.             }
  24.         }
  25.  
  26.         private static async Task<TResponse> ReadResponseAsync<TResponse>(HttpResponseMessage httpResponseMessage)
  27.         {
  28.             var response = await httpResponseMessage.Content.ReadAsAsync<dynamic>();
  29.  
  30.             switch (httpResponseMessage.StatusCode)
  31.             {
  32.             case HttpStatusCode.Accepted:
  33.             case HttpStatusCode.Created:
  34.             case HttpStatusCode.NonAuthoritativeInformation:
  35.             case HttpStatusCode.OK:
  36.             case HttpStatusCode.PartialContent:
  37.                 return response.ToString();
  38.             case HttpStatusCode.NoContent:
  39.                 return default(TResponse);
  40.             default:
  41.                 {
  42.                     return default(TResponse);
  43.                 }
  44.             }
  45.         }
  46.         public static void Main(string[] args)
  47.         {
  48.             Console.WriteLine("Hello World!");
  49.  
  50.             var res = SendAsync<string>(HttpMethod.Get);
  51.  
  52.             var f = res.Result;
  53.  
  54.             Console.WriteLine(f);
  55.  
  56.             Console.ReadLine();
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment