4

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.

Geek
  • 8,280
  • 17
  • 73
  • 137

1 Answers1

5

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.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Thank you for the explanation, but I don't get whether you mean I need to escape POST parameter or not. Also note that while setting HTTP body I do `postParameters.getBytes("UTF-8")` as shown in question. – Geek Jun 24 '13 at 15:08
  • What is the content of the variable `postParameter`? Give me an example? Also, what does your server API expect? – David Wasser Jun 24 '13 at 15:45
  • Example of postParamter is `name=Akash&email=example@example.com`. What do you mean by what does my server expects? – Geek Jun 24 '13 at 15:50
  • You can't just URL-encode the whole thing. You need to URL-encode only the "value" parts. In your example, "Akash" and "example@example.com" need to be URL-encoded. However, if you can be sure that no unacceptable characters will be present in those values, then you can skip the URL-encoding. – David Wasser Jun 24 '13 at 15:59
  • Ok. And what about escaping the postParameters? Do I need to escape it if I URL-encode it? – Geek Jun 24 '13 at 16:07
  • What do you mean "escape" it? I think you mean the same thing as URL-encoding. – David Wasser Jun 24 '13 at 16:20
  • By escaping I mean replacing few symbols such as $,@,space,%,#,etc... by its escape character equivalent. – Geek Jun 24 '13 at 16:27
  • That's exactly what URLencoding does. – David Wasser Jun 24 '13 at 16:28