JonCanning / TankTop

A lightweight, testable, .NET IndexTank implementation
5 stars 1 forks source link

TankTop's WebClient seems not to handle non-ASCII data when sending requests #5

Closed corneliuskopp closed 12 years ago

corneliuskopp commented 12 years ago

The WebClient class of TankTop seems not to handle UTF8 data, or even non-ASCII data at all. Cf. TankTop.WebClient.cs:78 var bytes = Encoding.ASCII.GetBytes(json) (see excerpt below).

My idea would be using Encoding.UTF8.GetBytes(json) in this place; the StreamReader used in the Send method assumes UTF8 by default as well.


namespace TankTop
{
    class WebClient : IWebClient
    {
        // [...]

        T Send<T>(string resource, string method, object request = null)
        {
            using (var webResponse = HttpWebResponse(resource, method, request))
            using (var responseStream = webResponse.GetResponseStream())
            using (var streamReader = new StreamReader(responseStream)) // <- this here, default encoding = UTF8
            {
                var json = streamReader.ReadToEnd();
                Response = json;
                return JsonSerializer.DeserializeFromString<T>(json);
            }
        }

        // [...]

        HttpWebResponse HttpWebResponse(string resource, string method, object request)
        {
            var webRequest = WebRequest.Create(baseAddress + resource).CastTo<HttpWebRequest>();    
            webRequest.Method = method;
            webRequest.Headers = webHeaderCollection;
            if (request != null)
            {
                using (var outputStream = webRequest.GetRequestStream())
                {
                    var json = request.SerializeToString();
                    var bytes = Encoding.ASCII.GetBytes(json); // <- this here, should be Encoding.UTF8.GetBytes()?
                    outputStream.Write(bytes, 0, bytes.Length);
                }
            }
            // [...]
        }
    }
}
JonCanning commented 12 years ago

Can't even make an excuse; that's just sloppy coding from me. Cheers.

corneliuskopp commented 12 years ago

Sorry for the late response; and thank you oncemore for the quick fix. :) TankTop gets ever more fun to use.