Why*_*ous 0 c# post urlencode httpwebrequest winforms
我在发送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); //server returns for wrong password.
wr.Close();
Run Code Online (Sandbox Code Playgroud)
第二种方法
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..
Run Code Online (Sandbox Code Playgroud)
我认为我在如何将url编码发送到请求方面做错了,我真的请求一些帮助,我通过谷歌搜索并找不到有关如何将编码的URL发送到HttpWebRequest的更多信息.我感谢你的时间和关注,希望你能帮助我.谢谢.
我推荐你一个WebClient.将缩短您的代码并处理编码和内容:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "username", "anyname" },
{ "password", "+13Gt2" },
};
var url = "http://foo.com";
var result = client.UploadValues(url, values);
}
Run Code Online (Sandbox Code Playgroud)
我发现我使用Uri.EscapeDataString它的答案完全解决了我的问题,但不知怎的,我无法做到HttpUtility.UrlEncode.Stackoverflowing,我发现这个问题是关于urlEncode方法,在msdn它的文档告诉:
对URL字符串进行编码.
但我现在知道如果用于编码POST数据是错误的(@Marvin,@ Polity,感谢更正).丢弃后,我尝试了以下方法:
string postData = String.Format("username={0}&password={1}", "anyname", Uri.EscapeDataString("+13Gt2"));
Run Code Online (Sandbox Code Playgroud)
POST数据转换为:
// **Output
string username = anyname;
string password = %2B13Gt2;
Run Code Online (Sandbox Code Playgroud)
Uri.EscapeDataString在msdn中说如下:
将字符串转换为其转义表示形式.
我认为这就是我所寻找的,当我尝试上述内容时,只要有数据包括formdata中的'+'字符,我就可以正确发布,但不知何故,有很多东西可以学习它们.
这个链接真的很有帮助.
非常感谢您的答案和时间,我非常感激.伙伴.
| 归档时间: |
|
| 查看次数: |
7369 次 |
| 最近记录: |