如何使用HttpWebRequest在POST中转义URL编码数据
我正在尝试将URL编码的post发送到用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
的用户,那么&符号应该如何转义以便它不会弄乱请求行?
您可以使用System.Web中的静态HttpUtility
类来编码和解码HTML和Url相关的值。
试试HttpUtility.UrlEncode()
。
似乎System.Web已经过时 – 访问它的新方法是System.Net.WebUtility.HtmlEncode
上述就是C#学习教程:如何使用HttpWebRequest在POST中转义URL编码数据分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/955830.html