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
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: