Web 客户端无法正确解释 WP7 中的输入字符
我在使用 WebClient.UploadStringAsync 方法时遇到问题。我必须向外部服务器发出包含一些信息的 POST 请求,并且在该请求中,我必须包含 TextBox 中包含的文本。
我所做的如下:
Uri url = new Uri("http://www.someweb.com");
string request = "{\"requests\":[\"sendMessage\",{\"body\":\"" + newMessageTextBox.Text + "\"}]}";
WebClient wb = new WebClient();
wb.UploadStringCompleted += new UploadStringCompletedEventHandler(nb_UploadStringCompleted);
wb.UploadStringAsync(url, "Post", request);
没有问题,但是如果我包含一条带返回的消息,例如 “
大家好” 服务器返回一个错误。如果我用 Wireshark 嗅探我的流量,我可以看到我的 POST 请求,但如下所示:
"{"requests":["sendMessage",{"body":"你好
大家“}]}”
而我想发送的是
"{"requests":["sendMessage",{"body":"Hello\n\neverbody"}]}"
有什么想法吗?
谢谢大家
I've got a problem using WebClient.UploadStringAsync method. I've to do a POST request with some info to an external server, and in that request, I've to include the text cointained in a TextBox.
What I do is the following:
Uri url = new Uri("http://www.someweb.com");
string request = "{\"requests\":[\"sendMessage\",{\"body\":\"" + newMessageTextBox.Text + "\"}]}";
WebClient wb = new WebClient();
wb.UploadStringCompleted += new UploadStringCompletedEventHandler(nb_UploadStringCompleted);
wb.UploadStringAsync(url, "Post", request);
There is no problem, but if I include a message with a return, something like
"Hello
everybody"
the server gives back an error. If I sniff my traffic with Wireshark, I can see my POST request but it is as follows:
"{"requests":["sendMessage",{"body":"Hello
everybody"}]}"
While what I want to send is
"{"requests":["sendMessage",{"body":"Hello\n\neverybody"}]}"
Any ideas??
Thank you all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您需要执行适当的 JSON 转义。就我个人而言,我会为此使用 JSON 库 - 我在 Windows Phone 7 中使用了 Json.NET 并且运行良好。
您可以将请求构建为 JSON 对象 - 因此根本不需要指定 JSON 文本表单本身 - 然后要求它将自身格式化为字符串(只需调用
ToString
)。例如:输出:(
显然,如果您不想,则不需要使用那么多的空白。您也不必使用对象初始值设定项。)
编辑:好的,根据要求进行更改:
结果:
Yes, you need to perform appropriate JSON escaping. Personally I would use a JSON library for this - I've used Json.NET within Windows Phone 7 and it's worked fine.
You'd build up your request as a JSON object - so without specifying the JSON text form itself at all - and then ask it to format itself into a string (just by calling
ToString
). For example:Output:
(Obviously you don't need to use as much whitespace as that if you don't want to. You don't have to use object initializers either.)
EDIT: Okay, with changes as requested:
Result: