C# Escape Plus Sign (+) in POST using HttpWebRequest

chttpwebrequestposturlencodewinforms

I'm having issues to send POST data that includes characteres like "+" in the password field,

string postData = String.Format("username={0}&password={1}", "anyname", "+13Gt2");

I'm using HttpWebRequest and a webbrowser to see the results, and when I try to log in from my C# WinForms using HttpWebRequest to POST data to the website, it tells me that password is incorrect. (in the source code[richTexbox1] and the webBrowser1). Trying it with another account of mine, that does not contain '+' character, it lets me log in correctly (using array of bytes and writing it to the stream)

byte[] byteArray = Encoding.ASCII.GetBytes(postData); //get the data
request.Method = "POST"; 
request.Accept = "text/html";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close(); //this works well if user does not includes symbols

From this Question I found that HttpUtility.UrlEncode() is the solution to escape illegal characters, but I can't find out how to use it correctly, my question is, after url-encoding my POST data with urlEncode() how do I send the data to my request correctly?

This is how I've been trying for HOURS to make it work, but no luck,

First method

string urlEncoded = HttpUtility.UrlEncode(postData, ASCIIEncoding.ASCII);
//request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlEncoded.Length;
StreamWriter wr = new StreamWriter(request.GetRequestStream(),ASCIIEncoding.ASCII);
wr.Write(urlEncoded); //server returns for wrong password.
wr.Close();

Second method

byte[] urlEncodedArray = HttpUtility.UrlEncodeToBytes(postData,ASCIIEncoding.ASCII);
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(urlEncodedArray, 0, urlEncodedArray.Length); // Send the data.
newStream.Close();  //The server tells me the same thing..

I think I'm doing wrong on how the url-encoded must be sent to the request, I really ask for some help please, I searched through google and couldn't find more info about how to send encoded url to an HttpWebRequest.. I appreciate your time and attention, hope you can help me. Thank you.

Best Answer

I'd recommend you a WebClient. Will shorten your code and take care of encoding and stuff:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    { 
        { "username", "anyname" },
        { "password", "+13Gt2" },
    };
    var url = "http://foo.com";
    var result = client.UploadValues(url, values);
}