Pierre Tasci
Pierre Tasci

Reputation: 450

Escaping reserved url parameters in Java

I am building an Android app and there is a part of the app where I need to post to a url with some form data. One of the form fields I pass along is an email address.

I noticed an issue where some email addresses have a '+' sign in them which is a reserved character in URLs that means ' '. I wanted to know, how can I sanitize/escape characters like this and others in my code before I convert it to a post byte[]. I don't want to do a replaceAll. Is there a specific encoder built into Java that will do this?

Here is the code I use:

StringBuilder builder = new StringBuilder();
builder.append(ID + "=" + params.id + "&");
builder.append(LOCALE + "=" + params.locale + "&");
builder.append(EMAIL + "=" + params.getEmail());

String encodedParams = builder.toString();
mWebView.postUrl(URL, EncodingUtils.getAsciiBytes(encodedParams));

Upvotes: 1

Views: 74

Answers (2)

Firefly
Firefly

Reputation: 5525

Try using java.net.URLEncoder.encode(valueToEncode, "UTF-8");

It's been a while since I've looked at the details, but I believe you have to call encode() on the individual parts of the string before you concatenate them.

The utility method below has been working well for me:

    /**
     * Given a {@link Map} of keys and values, this method will return a string
     * that represents the key-value pairs in
     * 'application/x-www-form-urlencoded' MIME format.
     * 
     * @param keysAndValues
     *            the keys and values
     * @return the data in 'application/x-www-form-urlencoded' MIME format
     */
    private String wwwFormUrlEncode(Map<String, String> keysAndValues) {
        try {
            StringBuilder sb = new StringBuilder();
            boolean isFirstEntry = true;
            for (Map.Entry<String, String> argument : keysAndValues.entrySet()) {
                if (isFirstEntry) {
                    isFirstEntry = false;
                } else {
                    sb.append("&");
                }
                sb.append(URLEncoder.encode(argument.getKey(), "UTF-8"));
                sb.append("=");
                sb.append(URLEncoder.encode(argument.getValue(), "UTF-8"));
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            //it is unlikely that the system does not support UTF-8 encoding, 
            //so we will not bother polluting the method's interface with a checked exception
            throw new RuntimeException(e); 
        }
    }

Upvotes: 2

Helmi
Helmi

Reputation: 556

Replace plus sign with %2b . you must encode it in order to use it in url or else it will be considered as space. then in your server side you can html decode emails.

Upvotes: 0

Related Questions