11

I am trying to send an URL-encoded post to a REST API implemented in PHP. The POST data contains two user-provided strings:

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

This sends a HTTP request to the server containing user=myusername&password=mypassword in UTF-8 as its POST data.

How can I escape the user-provided strings? For example, if I had a user named big&mean, how should the ampersand be escaped so that it does not mess up the request line?

Cygon
  • 9,444
  • 8
  • 42
  • 50

2 Answers2

17

You can use the static HttpUtility class in System.Web for encoding and decoding HTML and Url related values.

Try HttpUtility.UrlEncode().

womp
  • 115,835
  • 26
  • 236
  • 269
  • Thanks! If I use that method on a string containing UTF-8 characters, such as a german s-z, the UTF-8 code pair is turned into `%c3%9f`. I assume that means that the `Content-Transfer-Encoding` should be set to `7bit` now? – Cygon Jun 22 '10 at 09:38
  • One of the parameters you can provide with HttpUtility.UrlEncode is the Encoding. The character numbers used after the '%' depend on the encoding. – pauloya Jul 29 '10 at 08:11
-3

It would seem that System.Web is obsolete - the newer way to access it is System.Net.WebUtility.HtmlEncode

Glen Tankersley
  • 113
  • 1
  • 2
  • 1
    HtmlEncode is not the same as UrlEncode. HtmlEncode will convert "<" to "<", whereas UrlEncode will covert it to "%3c". – Sergey Feb 16 '15 at 21:56