Running the below code with Fiddler shows that plus signs are getting converted to a white space char of some sort. What encoding should I use to keep the data from being converted? I would like to keep the plus signs, etc.
EDIT: Updated code example
string postData = "test1=test+plussign&test2=another++twoplussigns";
private static byte[] EncodePostData(string postData)
{
StringBuilder sb = new StringBuilder();
string[] pairs = postData.Split('&');
foreach (string pair in pairs)
{
string key = Uri.EscapeDataString(pair.Split('=')[0]);
string value = Uri.EscapeDataString(pair.Split('=')[1]);
sb.AppendFormat("{0}={1}&",key, value);
}
sb.Remove(sb.Length - 1, 1);
return HttpUtility.UrlEncodeToBytes(sb.ToString());
}
And here is the calling method
byte[] data = EncodePostData(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.0.3) Gecko/2008092510 Ubuntu/8.04 (hardy) Firefox/3.03";
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
ServicePointManager.Expect100Continue = false;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse Response = (HttpWebResponse)request.GetResponse();
Response.Close();
Since your variable is called
postData, I’m going to assume you’re making a HTTP POST to a web server.Wikipedia’s summary of the rules for HTTP POST is:
That is, the default interpretation of
'+'in a HTTP POST body is an encoded' 'character. You need to escape your data properly, by calling Uri.EscapeDataString or HttpUtility.UrlEncode.Alternatively, use HttpUtility.UrlEncodeToBytes and write the resulting bytes directly to the request stream (without using a
StreamWriter).(Note that if you are sending key/value pairs, you need to escape each key and value independently, then join them with
'='and'&'characters.)