我在发送POST数据时遇到问题,包括密码字段中的"+"字符,
string postData = String.Format("username={0}&password={1}", "anyname", "+13Gt2");
Run Code Online (Sandbox Code Playgroud)
我正在使用HttpWebRequest和webbrowser来查看结果,当我尝试使用HttpWebRequest从我的C#WinForms 登录到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
Run Code Online (Sandbox Code Playgroud)
从这个问题我发现这HttpUtility.UrlEncode()
是逃避非法字符的解决方案,但我无法找到如何正确使用它,我的问题是,在对我的POST数据进行url编码后urlEncode()
如何正确地将数据发送到我的请求?
这就是我一直在尝试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); …
Run Code Online (Sandbox Code Playgroud)