【发布时间】:2014-11-14 10:07:53
【问题描述】:
我在与 .Net WPF 应用程序 (.Net 4.5) 中的 RESTful 服务进行通信时遇到了某种问题,尤其是在发送带有一些 json 数据的“PUT”请求时。
仅供参考:restful 服务正在 Python Flask 下运行。
方法我使用以下方法向restful服务发送请求:
HttpClient http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedCredentials);
http.Timeout = TimeSpan.FromSeconds(1);
// Add an Accept header for JSON format.
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(jDataString, Encoding.UTF8, "application/json");
当我提交通常的字符串时,一切正常。但是一旦字符串包含换行符,我就会遇到麻烦。
使用:
mytring.Replace("\r", "").Replace("\n", "")
工作,然后我的字符串被 restful 服务接受。
很遗憾,这是不可接受的,因为我希望能够检索换行符。
因此我尝试了以下方法:
mytring.Replace("\n", "\\n").Replace("\r", "\\r")
甚至使用内部字符来确保我能识别模式:
mytring.Replace("\n", "\\+n").Replace("\r", "\\+r")
在这两种情况下,我解析的字符串看起来都很好,但没有被 restful 服务接受。
以下两个示例 - 第一个版本被接受,而不是第二个和第三个......
"XML_FIELD": "<IDs><Id Type=\"System.Int32\" Value=\"7\" /></IDs>"
"XML_FIELD": "<IDs>\r\n<Id Type=\"System.Int32\" Value=\"20\" />\r\n</IDs>"
"XML_FIELD": "<IDs>\+r\+n<Id Type=\"System.Int32\" Value=\"20\" />\+r\+n</IDs>"
提前感谢您的帮助! 问候!
【问题讨论】:
标签: json wpf string rest special-characters