如何使用 HttpWebRequest 在 POST 中转义 URL 编码数据

发布于 2024-09-06 23:44:19 字数 1020 浏览 4 评论 0原文

我正在尝试将 URL 编码的帖子发送到用 PHP 实现的 REST API。 POST 数据包含两个用户提供的字符串:

WebRequest request = HttpWebRequest.Create(new Uri(serverUri, "rest"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Headers.Add("Content-Transfer-Encoding", "binary");

// Form the url-encoded credentials we'll use to log in
StringBuilder builder = new StringBuilder();
builder.Append("user=");
builder.Append(user);
builder.Append("&password=");
builder.Append(password);
byte[] credentials = Encoding.UTF8.GetBytes(builder.ToString());

// Write the url-encoded post data into the request stream.
request.ContentLength = credentials.Length;
using (Stream requestStream = request.GetRequestStream()) {
  requestStream.Write(credentials, 0, credentials.Length);
}

这将向服务器发送一个 HTTP 请求,其中包含 UTF-8 格式的 user=myusername&password=mypassword 作为其 POST 数据。

如何转义用户提供的字符串? 例如,如果我有一个名为 big&mean 的用户,应该如何转义 & 符号,以免弄乱请求行?

I am trying to send an URL-encoded post to a REST API implemented in PHP. The POST data contains two user-provided strings:

WebRequest request = HttpWebRequest.Create(new Uri(serverUri, "rest"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Headers.Add("Content-Transfer-Encoding", "binary");

// Form the url-encoded credentials we'll use to log in
StringBuilder builder = new StringBuilder();
builder.Append("user=");
builder.Append(user);
builder.Append("&password=");
builder.Append(password);
byte[] credentials = Encoding.UTF8.GetBytes(builder.ToString());

// Write the url-encoded post data into the request stream.
request.ContentLength = credentials.Length;
using (Stream requestStream = request.GetRequestStream()) {
  requestStream.Write(credentials, 0, credentials.Length);
}

This sends a HTTP request to the server containing user=myusername&password=mypassword in UTF-8 as its POST data.

How can I escape the user-provided strings?
For example, if I had a user named big&mean, how should the ampersand be escaped so that it does not mess up the request line?

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

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

发布评论

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

评论(2

人生百味 2024-09-13 23:44:20

您可以使用 System.Web 中的静态 HttpUtility 类来编码和解码 HTML 和 Url 相关值。

尝试HttpUtility.UrlEncode()

You can use the static HttpUtility class in System.Web for encoding and decoding HTML and Url related values.

Try HttpUtility.UrlEncode().

别再吹冷风 2024-09-13 23:44:20

System.Web 似乎已经过时了 - 访问它的新方法是 System.Net.WebUtility.HtmlEncode

It would seem that System.Web is obsolete - the newer way to access it is System.Net.WebUtility.HtmlEncode

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