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

时间:2010-06-21 23:24:55

标签: c# http httpwebrequest escaping urlencode

我正在尝试将一个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);
}

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

如何逃避用户提供的字符串? 例如,如果我有一个名为big&mean的用户,那么如何对&符号进行转义以使其不会弄乱请求行?

2 个答案:

答案 0 :(得分:17)

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

尝试HttpUtility.UrlEncode()

答案 1 :(得分:-3)

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