From: Gustavo Martin Date: Wed, 4 Jun 2014 04:36:06 +0000 (+0200) Subject: jsonrpc4net: encoding and check status X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=dfb63f0135f7203cdbe9c8a0bd629cb29f6d5230;p=CSharpForFun%2F.git jsonrpc4net: encoding and check status 1. retrieve received encoding from remote answer (and use it for local encoding) 2. check HTTP remote response status (using HttpResposeMessage.EnsureSuccessStatusCode) --- diff --git a/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs b/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs index aeee6fa..435466c 100644 --- a/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs +++ b/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs @@ -9,6 +9,7 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.IO; +using System.Text; namespace GumartinM.JsonRPC4NET { @@ -114,29 +115,41 @@ namespace GumartinM.JsonRPC4NET using (HttpContent contentPOST = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json-rpc")) // TODO: in WindowsPhone 8 client.PostAsync does not seem to spawn new thread :/ WTF // Using WindowsPhone 8 the result is returned in the same thread!!!!! WTF - using (HttpResponseMessage response = await client.PostAsync(uri, contentPOST, cancellation)) - //TODO: What if response is null? :( - using (HttpContent contentRESULT = response.Content) + using (HttpResponseMessage response = await client.PostAsync(uri, contentPOST, cancellation)) { - if (response.StatusCode == HttpStatusCode.OK) + //TODO: What if response is null? :( + response.EnsureSuccessStatusCode(); + + using (HttpContent contentRESULT = response.Content) { //TODO: What if contentRESULT is null? :( return await this.ReadResponseAsync(contentRESULT); } - - throw new Exception("Unexpected response code: " + response.StatusCode); } } async private Task> ReadResponseAsync(HttpContent content) { + /** + * Taken from HttpContent.cs ReadAsStringAsync() Mono implementation. + */ + Encoding encoding; + if (content.Headers != null && content.Headers.ContentType != null && content.Headers.ContentType.CharSet != null) + { + encoding = Encoding.GetEncoding(content.Headers.ContentType.CharSet); + } + else + { + encoding = Encoding.UTF8; + } + // Option a) with bytes //byte[] jsonBytes = await contentRESULT.ReadAsByteArrayAsync(); //return this.ReadResponse(jsonBytes); // Option b) with stream using (Stream stream = await content.ReadAsStreamAsync ()) - using (StreamReader streamReader = new StreamReader (stream, System.Text.Encoding.UTF8)) + using (StreamReader streamReader = new StreamReader(stream, encoding)) { // This line makes this method useless (IMHO it is the same as the one working with bytes) // How could I work with JSON saving memory?