c# – 如何使用HttpWebRequest在POST中转义URL编码的数据

前端之家收集整理的这篇文章主要介绍了c# – 如何使用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,credentials.Length);
}

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

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

解决方法

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

尝试HttpUtility.UrlEncode().

原文链接:https://www.f2er.com/csharp/97142.html

猜你在找的C#相关文章