-1

For each request to server in my android app I need to encode parameters, so my string for URL is looks like

"http://example.com/script.php?param1="+URLEncoder.encode(param1.getText().toString(), "UTF-8")+"param2="+URLEncoder.encode(param2.getText().toString(), "UTF-8")+...."

It works but maybe it is possible to use URLEncoder.encode only one time - like this

URLEncoder.encode("http://example.com/script.php?param1="+param1.getText().toString()+"param2="+param2.getText().toString()+....", "UTF-8")

Would it be ok or there are some cases when it can crash?

moonvader
  • 19,761
  • 18
  • 67
  • 116

2 Answers2

1

URL encoding the whole URL will not work, because it would result in something like

"http%3A%2F%2Fexample.com%2Fscript.php%3Fparam1%3Dasdf%26param2%3Djkl"

i.e. all the special characters in the whole URL would be encoded. You also can not url encode the whole query string, because the = and & characters would be encoded.

You have to encode each parameter value to stop special characters in the parameter interfering with the URL parsing. A helper function may reduce the pain.

String url = "http://example.com/script.php?" + encodeArgs("a", "a + b", "b", "=xxx=");

and something to get you started

public String encodeArgs(String... args) {
    final String encoding = "UTF-8";
    try {
        if (args.length % 2 != 0) {
            throw new IllegalArgumentException("number of arguments not even");
        }

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < args.length; i += 2) {
            sb.append(URLEncoder.encode(args[i], encoding));
            sb.append("=");
            sb.append(URLEncoder.encode(args[i + 1], encoding));
            sb.append("&");
        }

        // delete last &, if any
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }

        return sb.toString();

    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("unsupported encoding " + encoding, e);
    }
}
Juergen Gmeiner
  • 225
  • 2
  • 9
1

You should not encode complete URL. Encode only param section or in other words, only parts of it that come from "unreliable sources".

So your 1st attempt "http://example.com/script.php?param1="+URLEncoder.encode(param1.getText().toString(), "UTF-8")+"param2="+URLEncoder.encode(param2.getText().toString(), "UTF-8")+...." is correct, and you should continue with it.


URL encoding in Android and Android: howto parse URL String with spaces to URI object? can be useful for more clarity.

Community
  • 1
  • 1
Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186