【发布时间】:2011-12-15 09:03:11
【问题描述】:
我在发送密码字段中包含“+”等字符的 POST 数据时遇到问题,
string postData = String.Format("username={0}&password={1}", "anyname", "+13Gt2");
我正在使用 HttpWebRequest 和网络浏览器查看结果,当我尝试使用 HttpWebRequest 从我的 C# WinForms 登录 将数据发布到网站时,它告诉我密码不正确. (在源代码 [richTexbox1] 和 webBrowser1 中)。用我的另一个帐户尝试它,它不包含“+”字符,它可以让我正确登录(使用字节数组并将其写入流)
byte[] byteArray = Encoding.ASCII.GetBytes(postData); //get the data
request.Method = "POST";
request.Accept = "text/html";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close(); //this works well if user does not includes symbols
从Question我发现HttpUtility.UrlEncode()是转义非法字符的解决方案,但我不知道如何正确使用它,我的问题是,在使用urlEncode()对我的POST数据进行url编码后如何正确地将数据发送到我的请求?
这就是我一直在尝试 HOURS 使其工作的方法,但没有运气,
第一种方法
string urlEncoded = HttpUtility.UrlEncode(postData, ASCIIEncoding.ASCII);
//request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlEncoded.Length;
StreamWriter wr = new StreamWriter(request.GetRequestStream(),ASCIIEncoding.ASCII);
wr.Write(urlEncoded); //server returns for wrong password.
wr.Close();
第二种方法
byte[] urlEncodedArray = HttpUtility.UrlEncodeToBytes(postData,ASCIIEncoding.ASCII);
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(urlEncodedArray, 0, urlEncodedArray.Length); // Send the data.
newStream.Close(); //The server tells me the same thing..
我认为我在必须如何将 url 编码发送到请求方面做错了,我真的请求帮助,我通过谷歌搜索并找不到有关如何将编码的 url 发送到的更多信息HttpWebRequest.. 感谢您的时间和关注,希望您能帮助我。谢谢。
【问题讨论】:
-
您不必对发布数据进行编码。事实上,当你像这样对发布数据进行编码时,浏览器会错误地解释它。您的编码可能有问题。将 charset=ISO-8859-1 添加到您的内容类型,看看会发生什么
-
@Polity 首先感谢你让我明白,我找不到如何使用 urlEncode 来转义特殊字符,我试过你告诉我的(charset=ISO-8859-1)并且仍然有相同的结果,没有任何改变,我相信它在编码上,'+'被转换为空格。
标签: c# winforms post httpwebrequest urlencode