今天在用HttpWebResponse类向一个远程页面post数据时,遇到了一个怪问题:通过对比自己post的参数和服务器接收到的值,发现参数中的一个+号被替换成了空格。
造成这个错误的原因在于+号在url中是特殊字符,远程服务器在接受request的时候,把+转成了空格。同样的,如果想post的数据中有&、%等等,也会被服务器转义,所以我们在post的数据的时候,需要先把数据UrlEncode一下。url encode在bs开发中本来是一个很常见的问题。
修改后的post数据的示例代码如下:
public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } var postData = string.Join("&", parameters.Select( p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value, requestEncoding))).ToArray()); byte[] data = requestEncoding.GetBytes(postData); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; }