在UWP中接收来自HttpClient的响应时的错误编码

时间:2016-01-27 21:28:08

标签: c# xml rest encoding uwp

我正在制作uwp(通用Windows平台)应用程序,并希望将此xml:http://radioa24.info/ramowka.php反序列化为对象,但我得到了scpecial字符作为ł,ó一些奇怪的字母和特殊的字母,如:\ n和\ r:     “一个......”=> “中A”     “ć”=> “中C”     “Ä™”=> “中ê” 例如,Poniedziałek取代PoniedziaÅ\u0082ek

而不是var httpClient = new HttpClient(); var response = await httpClient.GetAsync(uri).AsTask(); response.EnsureSuccessStatusCode(); var result = await httpResponse.Content.ReadAsStringAsync();

我的代码:

var reader = new XmlSerializer(typeof(Sources.Schedule));
using (var tr = new MemoryStream(Encoding.UTF8.GetBytes(resultString)))
{
   Schedule = (Sources.Schedule)reader.Deserialize(res);
}

我试图制作一些编码转换,但没有成功。 如何解决它,因为后来我想得到我的对象?

database.php

3 个答案:

答案 0 :(得分:5)

请您尝试下面的代码,读取数据,因为字节可以解决您的问题。

using (HttpClient client = new HttpClient())
{
    Uri url = new Uri("http://radioa24.info/ramowka.php");
    HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, url);
    Task<HttpResponseMessage> responseAsync = client.SendRequestAsync(httpRequest).AsTask();
    responseAsync.Wait();
    responseAsync.Result.EnsureSuccessStatusCode();

    Task<IBuffer> asyncBuffer = responseAsync.Result.Content.ReadAsBufferAsync().AsTask();
    asyncBuffer.Wait();
    byte[] resultByteArray = asyncBuffer.Result.ToArray();
    string responseString = Encoding.UTF8.GetString(resultByteArray, 0, resultByteArray.Length);

    responseAsync.Result.Dispose();
}

答案 1 :(得分:1)

这是我的例子,与波兰语单词一起使用。

从页面获取xml的方法:

    public async Task<string> GetXMl(string uri)
    {
        string result = null;
        using (HttpClient httpClient = new HttpClient())
        {
            var response = await httpClient.GetAsync(uri);
            result = await response.Content.ReadAsStringAsync();
        }
        return result;
    }

反序列化xml的方法:

    public void DeserializeXml(string xml)
    {
        var serializer = new XmlSerializer(typeof(ramowka));
        var buffer = Encoding.UTF8.GetBytes(xml);
        using (var stream = new MemoryStream(buffer))
        {
            var ramowka = (ramowka)serializer.Deserialize(stream);
        }
    }

示例如何使用方法,例如在按钮单击事件中:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        string xml = await GetXMl("http://radioa24.info/ramowka.php");
        DeserializeXml(xml);
    }

此外,您还可以通过Visual Studio xml转换为C#类 http://pastebin.com/aJ4B1aCF

答案 2 :(得分:1)

正如Jon Skeet在his answer中所说,这应该在服务器上修复。如果您检查服务器,则发送回以下Content-Type标头:

Content-Type: text/xml

它应该告诉你编码(Content-Type: text/xml; charset=utf-8),这就是它应该是服务器修复的原因。

但如果你确定这是UTF-8(因为响应xml包含<?xml version="1.0" encoding="UTF-8"?>),你可以这样做:

var httpClient = new HttpClient();
var response = await httpClient.GetBufferAsync(uri);
var bytes = response.ToArray();
var properEncodedString = Encoding.UTF8.GetString(bytes);