c#使用特殊字符发送请求会干扰字符串

时间:2013-01-01 16:16:39

标签: c# .net httpwebrequest request

我将一个项目的请求从解决方案发送给另一个项目:

WebRequest request = WebRequest.Create(UrlTemplate);
request.Timeout = 500000;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = ContentType;
byte[] postData = System.Text.Encoding.ASCII.GetBytes(data);
request.ContentLength = postData.Length;
Stream newStream = request.GetRequestStream();
// Send the data.
newStream.Write(postData, 0, postData.Length);
newStream.Flush();
newStream.Close();

好吧,在UrlTemplate中设置的函数中,我得到了正确的字符串(我在数据中发送),但是当字符串包含特殊字符时问题就开始了。

如果字符串是:12&34

我在函数中得到的是:12

如果字符串是:12+34

我在函数中得到的是:12 34

我很高兴知道你们中的一些人是否已经发生过以及你们是如何解决的。提前谢谢。

3 个答案:

答案 0 :(得分:7)

在形成UrlTemplate时使用System.Web.HttpUtility.UrlEncodeSystem.Net.WebUtility.UrlEncode

答案 1 :(得分:2)

问题是由于字符串为url-form Encoded而引起的。 (如果这只是一个GET,我会说它是URL编码的,但你正在使用POST。)& sign在URL中具有特殊含义,+符号用作替换空格。

有关规格,请参阅http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.3。如果您想获得您期望的结果,则需要使用UrlEncode()手动对这些进行编码。

答案 2 :(得分:1)

在密码中使用URI.EscapeDataString()方法。它将帮助您正确阅读特殊字符。