Remark :
Console with Http and Json
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
using Newtonsoft.Json; using System; using System.IO; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using System.Collections.Generic; namespace SystemNetHttpJsonSamples { partial class Program { static async Task Main() { const string validUserUri = "https://example.com/users/1"; const string postUserUri = "https://example.com/users"; var httpClient = new HttpClient(new FakeEndpointHandler()); User user = null; user = await InefficientStringApproach(validUserUri, httpClient); user = await StreamWithNewtonsoftJson(validUserUri, httpClient); user = await WebApiClient(validUserUri, httpClient); user = await StreamWithSystemTextJson(validUserUri, httpClient); user = await GetJsonHttpClient(validUserUri, httpClient); user = await GetJsonFromContent(validUserUri, httpClient); await PostJsonHttpClient(postUserUri, httpClient); await PostJsonContent(postUserUri, httpClient); _ = Console.ReadLine(); } private static async Task<User> InefficientStringApproach(string uri, HttpClient httpClient) { var httpResponse = await httpClient.GetAsync(uri); if (httpResponse.Content is object && httpResponse.Content.Headers.ContentType.MediaType == "application/json") { var jsonString = await httpResponse.Content.ReadAsStringAsync(); //Console.WriteLine("OK"); return JsonConvert.DeserializeObject<User>(jsonString); } else { Console.WriteLine("HTTP Response was invalid and cannot be deserialised."); } return null; } private static async Task<User> StreamWithNewtonsoftJson(string uri, HttpClient httpClient) { using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead); httpResponse.EnsureSuccessStatusCode(); // throws if not 200-299 if (httpResponse.Content is object && httpResponse.Content.Headers.ContentType.MediaType == "application/json") { var contentStream = await httpResponse.Content.ReadAsStreamAsync(); using var streamReader = new StreamReader(contentStream); using var jsonReader = new JsonTextReader(streamReader); JsonSerializer serializer = new JsonSerializer(); try { return serializer.Deserialize<User>(jsonReader); } catch(JsonReaderException) { Console.WriteLine("Invalid JSON."); } } else { Console.WriteLine("HTTP Response was invalid and cannot be deserialised."); } return null; } private static async Task<User> WebApiClient(string uri, HttpClient httpClient) { using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead); httpResponse.EnsureSuccessStatusCode(); // throws if not 200-299 try { return await httpResponse.Content.ReadAsAsync<User>(); } catch // Could be ArgumentNullException or UnsupportedMediaTypeException { Console.WriteLine("HTTP Response was invalid or could not be deserialised."); } return null; } private static async Task<User> StreamWithSystemTextJson(string uri, HttpClient httpClient) { using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead); httpResponse.EnsureSuccessStatusCode(); // throws if not 200-299 if (httpResponse.Content is object && httpResponse.Content.Headers.ContentType.MediaType == "application/json") { var contentStream = await httpResponse.Content.ReadAsStreamAsync(); try { return await System.Text.Json.JsonSerializer.DeserializeAsync<User>(contentStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true }); } catch (JsonException) // Invalid JSON { Console.WriteLine("Invalid JSON."); } } else { Console.WriteLine("HTTP Response was invalid and cannot be deserialised."); } return null; } private static async Task<User> GetJsonHttpClient(string uri, HttpClient httpClient) { try { var user = await httpClient.GetFromJsonAsync<User>(uri); return user; } catch (HttpRequestException) // Non success { Console.WriteLine("An error occurred."); } catch (NotSupportedException) // When content type is not valid { Console.WriteLine("The content type is not supported."); } catch (JsonException) // Invalid JSON { Console.WriteLine("Invalid JSON."); } return null; } private static async Task<User> GetJsonFromContent(string uri, HttpClient httpClient) { var request = new HttpRequestMessage(HttpMethod.Get, uri); request.Headers.TryAddWithoutValidation("some-header", "some-value"); using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { // perhaps check some headers before deserialising try { return await response.Content.ReadFromJsonAsync<User>(); } catch (NotSupportedException) // When content type is not valid { Console.WriteLine("The content type is not supported."); } catch (JsonException) // Invalid JSON { Console.WriteLine("Invalid JSON."); } } return null; } private static async Task PostJsonHttpClient(string uri, HttpClient httpClient) { var postUser = new User { Name = "Steve Gordon" }; var postResponse = await httpClient.PostAsJsonAsync(uri, postUser); postResponse.EnsureSuccessStatusCode(); } private static async Task PostJsonContent(string uri, HttpClient httpClient) { var postUser = new User { Name = "Steve Gordon" }; var postRequest = new HttpRequestMessage(HttpMethod.Post, uri) { Content = JsonContent.Create(postUser) }; var postResponse = await httpClient.SendAsync(postRequest); postResponse.EnsureSuccessStatusCode(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace SystemNetHttpJsonSamples { public class Address { public string Street { get; set; } public string City { get; set; } public string Postcode { get; set; } public Geo Geo { get; set; } } } |
1 2 3 4 5 6 7 8 9 10 |
namespace SystemNetHttpJsonSamples { public class Company { public string Name { get; set; } public string CatchPhrase { get; set; } } } |
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 |
using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SystemNetHttpJsonSamples { partial class Program { internal class FakeEndpointHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage responseMessage = null; if (request.Method == HttpMethod.Get && request.RequestUri.AbsolutePath == "/users/1") { responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent("{\"id\":1,\"name\":\"Steve Gordon\",\"username\":\"stevejgordon\",\"email\":\"stevejgordon@example.com\",\"address\":{\"street\":\"1 Madeup Place\",\"city\":\"Sometown\",\"postcode\":\"AA1 1AA\",\"geo\":{\"lat\":\"0.0000\",\"lng\":\"0.0000\"}},\"phone\":\"00000 000000\",\"website\":\"stevejgordon.co.uk\",\"company\":{\"name\":\"An Impressive Name\",\"catchPhrase\":\"Building .NET Code everyday!\"}}", Encoding.UTF8, "application/json") }; } if (request.Method == HttpMethod.Get && request.RequestUri.AbsolutePath == "/users/2") { responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound); } if (request.Method == HttpMethod.Post && request.RequestUri.AbsolutePath == "/users") { responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.Created); } return Task.FromResult(responseMessage); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
namespace SystemNetHttpJsonSamples { public class User { public int Id { get; set; } public string Name { get; set; } public string Username { get; set; } public string Email { get; set; } public Address Address { get; set; } public string Phone { get; set; } public string Website { get; set; } public Company Company { get; set; } } } |
1 2 3 4 5 6 7 8 9 10 |
namespace SystemNetHttpJsonSamples { public class Geo { public string Lat { get; set; } public string Lng { get; set; } } } |