我试图将一个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数据.
解决方法
您可以使用System.Web中的静态HttpUtility类对HTML和Url相关值进行编码和解码.
尝试HttpUtility.UrlEncode().