URL encoding in Android

How do you code in Android URL

I think it's like this:

final String encodedURL = URLEncoder.encode(urlAsString, "UTF-8");
URL url = new URL(encodedURL);

If I do the above, http: / / in urlAsString is replaced by http%3A%2F%2F in encoded URL, and then I get a java.net.MalformedURLException when I use the URL.

#1 building

For Android, I'll use String android.net.Uri.encode (String s)

Use the UTF-8 scheme to encode characters in a given string as octets escaped by '%'. Reserved letters ("AZ", "AZ"), numbers ("0-9") and unreserved characters ("-!. ~ '() *") are intact. Encode all other characters.

Case /

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

#2 building

You can also use this

private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);

This is the easiest way

#3 building

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block

#4 building

You don't need to encode the entire URL, only a part of it from an "unreliable source.".

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;

In addition, you can use the Droid parts Strings.urlEncode(String str) .

Or use similar

String uri = Uri.parse("http://...")
                .appendQueryParameter("key", "val")

#5 building

You can use the following methods

public static String parseUrl(String surl) throws Exception
    URL u = new URL(surl);
    return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();


public String parseURL(String url, Map<String, String> params)
    Builder builder = Uri.parse(url).buildUpon();
    for (String key : params.keySet())
        builder.appendQueryParameter(key, params.get(key));
    return builder.build().toString();

The second is better than the first.

Tags: Android Java

Posted on Fri, 13 Mar 2020 10:39:32 -0400 by roliver