Search code examples
javaandroidescapinghttpurlconnectionpost-parameter

Do I need to escape a string which is post parameters to pass in HTTP body?


I use HTTPUrlConnection to request a REST API.
I ser "Content-type" header as follows :

urlConnection.setRequestProperty("Content-type",
                        "application/x-www-form-urlencoded");

I set HTTP body as follows :

out = urlConnection.getOutputStream();
out.write(postParameters.getBytes("UTF-8"));

I don't know if I need to escape post parameters(which is a String) when I set HTTP header and body as shown above.

I just need Yes or No as answer, but would be great if the answer explains why yes or why no.


Solution

  • Since the data you are POSTing is to be interpreted as application/x-www-form-urlencoded, then it must have the form:

    name1=value1&name2=value2&...
    

    Therefore, the "value" parts MUST be URL-encoded, otherwise they will not be interpreted correctly.

    Using POST with x-www-form-urlencoded is just moving the query-string part of the URL out of the request and into the body.