在REST API解析中使用带重音的字符

时间:2016-01-11 03:09:04

标签: c# parse-platform

我正在使用解析来发送推送消息。我创建了一个简单的工具,允许管理员向用户发送消息。

这个函数工作正常,当我将一个像“Vocêrecebeuuma mensagem”这样的字符串传递给pushMessage变量时会出现问题。这是因为我使用了字符“^”。如果我在解析推送面板中使用相同的字符串,则会发送消息。

如何解析字符串以防止在C#中出现此问题?

Parse.cs

  private bool PushNotification(string pushMessage, string title, string canais)
    {
        bool isPushMessageSend = false;

    string postString = "";
    string urlpath = "https://api.parse.com/1/push";
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
    /*postString = "{ \"channels\":"+ canais +", " +
                     "\"data\" : {\"alert\":\"" + pushMessage + "\"}" +
                     "}";*/
   /* postString = "{ \"channels\":"+ canais +", " +
    "\"data\": {\"message\": \"" + pushMessage + "\",\"title\": \"" + title + "\",\"is_background\": false}}";*/
    postString = "{ \"channels\":" + canais + ", " +
   "\"data\": {\"data\": {\"message\": \""+pushMessage+"\",\"title\": \""+title+"\"},\"is_background\": \"false\"}}";

    httpWebRequest.ContentType = "application/json";
    httpWebRequest.ContentLength = postString.Length;
    httpWebRequest.Headers.Add("X-Parse-Application-Id", "xxxxxxxxxxxxxx");
    httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "xxxxxxxxxxxxxxx");
    httpWebRequest.Method = "POST";
    StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
    requestWriter.Write(postString);
    requestWriter.Close();
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    try
    {
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            if(responseText.Contains("true"))
            {
                MessageBox.Show("Mensagem enviada com sucesso");
            }

        }
    }catch(Exception e)
    {
        MessageBox.Show("Problema ao enviar mensagem\nErro:"+e.ToString());
    }

    reset();
    return isPushMessageSend;
}

2 个答案:

答案 0 :(得分:1)

使用JSON时我会坚持使用UTF-8。

httpWebRequest.ContentType = "application/json; charset=utf-8";

并以字节为单位输入正确的ContentLength,其中包含编码格式:

httpWebRequest.ContentLength = Encoding.UTF8.GetBytes(postString).Length;
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream()); //UTF-8 by default

完整示例Here

enter image description here

正如您在screenShot中看到的那样,“ê”字符在UTF8中被加入八进制值\ 303 \ 252,您可以在this table中看到这对应于:带有CIRCUMFLEX的LATIN SMALL LETTER

如果服务器无法解析它,那么它就有一个很大的问题,因为解析UTF-8就像是互联网上的面包和黄油。

答案 1 :(得分:0)

您需要在发送之前对pushMessage进行编码,并要求前端开发人员在JSON中解码消息属性