使用HTTPRequest以JSON格式发送变音符号

时间:2015-07-10 09:37:43

标签: c# json http

我正在尝试使用POST将JSON字符串发送到在Azure上运行的Web服务。该程序是使用Xamarin Forms创建的应用程序。 与服务器的JSON通信基本上可以工作,但我的变音符号有问题。

我有一堂课“考试”

public class Test
{
    public string ä { get; set; }            
}

我尝试序列化为一个字符串。我使用JsonConvert:

string postData = JsonConvert.SerializeObject(test);

这导致{“ä”:“ä”}。

当我发送此字符串时,我收到400 Bad Request错误消息。

有趣的是,使用Firefox插件“Open HttpRequester”发送此字符串非常有效。

将第一个变音符号更改为“ae”({“ae”:“ä”})虽然有效。

这里是我用来发送字符串的C#代码:

private void Send()
{
    Uri uri = new Uri(serverPath);
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
    request.Method = "POST";
    request.ContentType = "application/json";
    request.BeginGetRequestStream(new AsyncCallback(UploadWithRequestStream), request);
}

private void UploadWithRequestStream(IAsyncResult asynchronousResult)
{
    Test test = new Test();
    test.ä = "ä";
    string postData = JsonConvert.SerializeObject(test); // {"ä":"ä"}

    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
    Stream uploadStream = request.EndGetRequestStream(asynchronousResult);
    uploadStream.Write(byteArray, 0, postData.Length);
    uploadStream.Flush();
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

private void GetResponseCallback(IAsyncResult asynchronousResult)
{
    // 404 Bad Request
}

1 个答案:

答案 0 :(得分:3)

嗯,你在这一行中遇到了问题:

uploadStream.Write(byteArray, 0, postData.Length);

您从byteArray上传字节并将其计为字符。但是单个char(特别是变音符号)可以映射到两个字节。在您的示例中,byteArray.Length = 11,postData.Length = 9.这就是您发送缩短版postData的原因,服务器无法处理它。

用下面的字符串替换上面提到的字符串,一切都很好:

uploadStream.Write(byteArray, 0, byteArray.Length);