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

标签 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);
}

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

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

最佳答案

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

试试 HttpUtility.UrlEncode()

关于c# - 如何使用 HttpWebRequest 转义 POST 中的 URL 编码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3089177/

相关文章:

c# - 通过 HTTPS 的 HttpWebRequest 的随机问题

c# - .NET 如何发送 HttpClient 获取同一域中指定 IP 地址的请求

.net - 如何在特定的 HttpWebRequest 中使用 SSL3 而不是 TLS?

c# - Twilio 休息 API 错误代码 21612

c# - IDX10501 : Signature validation failed. 尝试的 key : 'System.IdentityModel.Tokens.X509AsymmetricSecurityKey'

c# - 为什么 MVC 会在看似没有 Null Reference 的情况下抛出 NullReferenceException?

javascript - 如何使用随机字符串作为路由参数(ExpressJS)

http - play framework 同时运行多个项目

c++ - 如何从 libcurl 中的 http header 中删除 Accept

c# - 如何使用 C# mongodb 在 linq 中使用小写字母