[英]How to escape URL-encoded data in POST with HttpWebRequest
I am trying to send an URL-encoded post to a REST API implemented in PHP. 我正在尝试将URL编码的帖子发送到用PHP实现的REST API。 The POST data contains two user-provided strings:
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);
}
This sends a HTTP request to the server containing user=myusername&password=mypassword
in UTF-8 as its POST data. 这会向服务器发送一个HTTP请求,其中包含UTF-8中的
user=myusername&password=mypassword
作为其POST数据。
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? 例如,如果我有一个名为
big&mean
的用户,那么&符号应该如何转义以便它不会弄乱请求行?
You can use the static HttpUtility
class in System.Web for encoding and decoding HTML and Url related values. 您可以使用System.Web中的静态
HttpUtility
类来编码和解码HTML和Url相关的值。
Try HttpUtility.UrlEncode()
. 试试
HttpUtility.UrlEncode()
。
看起来System.Web已经过时了 - 访问它的新方法是System.Net.WebUtility.HtmlEncode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.