我在发送密码字段中包含“+”等字符的 POST 数据时遇到问题,
string postData = String.Format("username={0}&password={1}", "anyname", "+13Gt2");
我正在使用 HttpWebRequest 和网络浏览器来查看结果,当我尝试log in从我的 C# WinForms 使用 HttpWebRequest 将数据 POST 到网站时,它告诉我密码不正确。 (在源代码[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 https://stackoverflow.com/questions/3089177/how-to-escape-url-encoded-data-in-post-with-httpwebrequest我找到HttpUtility.UrlEncode()
是转义非法字符的解决方案,但我不知道如何正确使用它,我的问题是,在对我的 POST 数据进行 url 编码后urlEncode()
我如何将数据发送到我的request正确吗?
这就是我花了几个小时努力让它发挥作用的方法,但没有运气,
第一种方法
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 编码发送到请求上做错了,我真的需要一些帮助,我通过 google 搜索,找不到有关如何将编码 url 发送到 HttpWebRequest 的更多信息。感谢您的时间和关注,希望您能帮助我。谢谢。