Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape URL-encoded data in POST with HttpWebRequest

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?

like image 684
Cygon Avatar asked Jun 21 '10 23:06

Cygon


People also ask

How do you escape space in URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is URL encoded string?

URL Encoding is the process of converting string into valid URL format. Valid URL format means that the URL contains only what is termed "alpha | digit | safe | extra | escape" characters.

Do I need to Urlencode post data?

General Answer. The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers. A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string.

What is urlencoded format?

URL Encoding is the process of converting string into valid URL format. Valid URL format means that the URL contains only what is termed "alpha | digit | safe | extra | escape" characters.


1 Answers

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

Try HttpUtility.UrlEncode().

like image 72
womp Avatar answered Oct 16 '22 10:10

womp