C# 使用 HttpWebRequest 在 POST 中转义加号 (+)

发布于 2024-12-21 03:17:47 字数 2124 浏览 1 评论 0 原文

我在发送密码字段中包含“+”等字符的 POST 数据时遇到问题,

string postData = String.Format("username={0}&password={1}", "anyname", "+13Gt2");

我正在使用 HttpWebRequest 和网络浏览器来查看结果,并且当我尝试从我的帐户登录时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

从此 问题 我发现 HttpUtility.UrlEncode() 是以下问题的解决方案转义非法字符,但我不知道如何正确使用它,我的问题是,使用 urlEncode() 对我的 POST 数据进行 url 编码后,如何将数据发送到我的 请求正确吗?

这就是我花了几个小时努力让它发挥作用的方法,但没有运气,

第一种方法

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 发送到 HttpWebRequest 的更多信息。感谢您的时间和关注,希望您能帮助我。谢谢。

I'm having issues to send POST data that includes characteres like "+" in the password field,

string postData = String.Format("username={0}&password={1}", "anyname", "+13Gt2");

I'm using HttpWebRequest and a webbrowser to see the results, and when I try to log in from my C# WinForms using HttpWebRequest to POST data to the website, it tells me that password is incorrect. (in the source code[richTexbox1] and the webBrowser1). Trying it with another account of mine, that does not contain '+' character, it lets me log in correctly (using array of bytes and writing it to the stream)

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

From this Question I found that HttpUtility.UrlEncode() is the solution to escape illegal characters, but I can't find out how to use it correctly, my question is, after url-encoding my POST data with urlEncode() how do I send the data to my request correctly?

This is how I've been trying for HOURS to make it work, but no luck,

First method

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();

Second method

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..

I think I'm doing wrong on how the url-encoded must be sent to the request, I really ask for some help please, I searched through google and couldn't find more info about how to send encoded url to an HttpWebRequest.. I appreciate your time and attention, hope you can help me. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我的痛♀有谁懂 2024-12-28 03:17:47

我使用 Uri.EscapeDataString 找到了答案,它完全解决了我的问题,但不知怎的,我无法使用 HttpUtility.UrlEncode 做到这一点。 在 Stackoverflow 周围,我发现了这个关于 urlEncode 的问题方法,在 msdn 它文档告诉我们:

对 URL 字符串进行编码。

但我现在知道,如果用于编码 POST 数据,这是错误的(@Marvin,@Polity,感谢您的更正)。丢弃它后,我尝试了以下操作:

string postData = String.Format("username={0}&password={1}", "anyname", Uri.EscapeDataString("+13Gt2"));

POST 数据转换为:

// **Output
string username = anyname;
string password = %2B13Gt2;

msdn 说明如下:

将字符串转换为其转义表示形式。

我认为这就是我正在寻找的,当我尝试上述操作时,只要表单数据中存在包含“+”字符的数据,我就可以正确发布,但不知何故存在关于他们有很多值得学习的地方。

这个链接真的很有帮助。

http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

非常感谢您的回答和您的时间,我非常感激。问候伙伴们。

I found my answer using Uri.EscapeDataString it exactly solved my problem, but somehow I couldn't do it with HttpUtility.UrlEncode. Stackoverflowing around, I found this question that is about urlEncode method, in msdn it documentation tells that:

Encodes a URL string.

But I know now that is wrong if used to encode POST data (@Marvin, @Polity, thanks for the correction). After discarding it, I tried the following:

string postData = String.Format("username={0}&password={1}", "anyname", Uri.EscapeDataString("+13Gt2"));

The POST data is converted into:

// **Output
string username = anyname;
string password = %2B13Gt2;

Uri.EscapeDataString in msdn says the following:

Converts a string to its escaped representation.

I think this what I was looking for, when I tried the above, I could POST correctly whenever there's data including the '+' characters in the formdata, but somehow there's much to learn about them.

This link is really helpful.

http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

Thanks a lot for the answers and your time, I appreciate it very much. Regards mates.

↘紸啶 2024-12-28 03:17:47

我向您推荐 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);
}

I'd recommend you a WebClient. Will shorten your code and take care of encoding and stuff:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    { 
        { "username", "anyname" },
        { "password", "+13Gt2" },
    };
    var url = "http://foo.com";
    var result = client.UploadValues(url, values);
}
终陌 2024-12-28 03:17:47

您发送的 postdata 不应进行 URL 编码!它是表单数据,而不是 URL。

  string url = @"http://localhost/WebApp/AddService.asmx/Add";
  string postData = "x=6&y=8";

  WebRequest req = WebRequest.Create(url);
  HttpWebRequest httpReq = (HttpWebRequest)req;

  httpReq.Method = WebRequestMethods.Http.Post;
  httpReq.ContentType = "application/x-www-form-urlencoded";
  Stream s = httpReq.GetRequestStream();
  StreamWriter sw = new StreamWriter(s,Encoding.ASCII);
  sw.Write(postData);
  sw.Close();

  HttpWebResponse httpResp = 
                 (HttpWebResponse)httpReq.GetResponse();
  s = httpResp.GetResponseStream();
  StreamReader sr = new StreamReader(s, Encoding.ASCII);
  Console.WriteLine(sr.ReadToEnd());

它使用 System.Text.Encoding.ASCII 对 postdata 进行编码。

希望这有帮助,

the postdata you are sending should NOT be URL encoded! it's formdata, not the URL

  string url = @"http://localhost/WebApp/AddService.asmx/Add";
  string postData = "x=6&y=8";

  WebRequest req = WebRequest.Create(url);
  HttpWebRequest httpReq = (HttpWebRequest)req;

  httpReq.Method = WebRequestMethods.Http.Post;
  httpReq.ContentType = "application/x-www-form-urlencoded";
  Stream s = httpReq.GetRequestStream();
  StreamWriter sw = new StreamWriter(s,Encoding.ASCII);
  sw.Write(postData);
  sw.Close();

  HttpWebResponse httpResp = 
                 (HttpWebResponse)httpReq.GetResponse();
  s = httpResp.GetResponseStream();
  StreamReader sr = new StreamReader(s, Encoding.ASCII);
  Console.WriteLine(sr.ReadToEnd());

This uses the System.Text.Encoding.ASCII to encode the postdata.

Hope this helps,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文