如何使用 HttpWebRequest 在 POST 中转义 URL 编码数据
我正在尝试将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 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()
.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