简体   繁体   中英

Encode both parameter and value or just value in URL for http post?

I have a Java class that submits http post request. I have query parameters and my question is do I need to encode both name=value pairs or just value.

String query = "foo=abc&bar=efg";

String encodedQuery = URLEncoder.encode("foo=abc&bar=efg","utf-8");

OR

String query = "foo=" + URLEncoder.encode("abc","utf-8") + "&" + "bar=" + URLEncoder.encode("efg","utf-8");

URLEncoder.encode is called to ensure that there are no unsafe chars in your URI. an unsafe char is nearly every char which is not a letter, a digit and some special chars.

From the java-doc of the URLEncoder

The alphanumeric characters "a" through "z", "A" through "Z" and "0" through >"9" remain the same. The special characters ".", "-", "*", and "_" remain the same. The space character " " is converted into a plus sign "+". All other characters are unsafe and are first converted into one or more bytes >using some encoding scheme. Then each byte is represented by the 3-character >string "%xy", where xy is the two-digit hexadecimal representation of the byte. >The recommended encoding scheme to use is UTF-8. However, for compatibility >reasons, if an encoding is not specified, then the default encoding of the >platform is used.

Example:

String query = "foo=abc&bar=def";

so. if you encode the whole query it will result in

foo%3Dabc%26bar%3Defg

In this case you also encoded the = and & which are needed to seperate the parts of the query.

You have to encode the names and value of your query to ensure that they do not contain unsafe chars. eg &, = and any non printable/special char. if you know, that your name only contains safe chars, you don't have to encode the name.

String param1 = URLEncoder.encode("abc", "utf-8");
String param2 = URLEncoder.encode("a&b", "utf-8");
String query = "foo=" + param1 + "&bar=" + param2;

results in

foo=abc&bar=a%26b

which should be the query you need. please note the & in param2 which will be encoded, cause it is "unsafe" for an valid url!

You should always encode the entire URL. So to answer your question, you should encode the entire query.

In fact a simpler way to encode would be to build the full URL using a URI. So with your query variable

URI uri = new URI(
    "http", 
    "example.com", 
    "/path",
    query,
    null);

URL url = uri.toURL();
// ... then open the HttpURLConnection

Please not that the above code does not perform the appropriate escape sequences on non-ASCII characters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM