Search code examples
androidutf-8url-encoding

Should I use URLEncoder for each URL parametr


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?


Solution

  • 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);
        }
    }