Android URL Decode decodeUrl(String url)

Here you can find the source of decodeUrl(String url)

Description

Decodes the specified URL as per RFC 3986, i.e.

License

Apache License

Parameter

Parameter Description
url The URL to decode, may be <code>null</code>.

Return

The decoded URL or null if the input was null.

Declaration

static String decodeUrl(String url) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
    /**/*from w ww  . j  a  v  a 2  s. c  o m*/
     * The UTF-8 character set, used to decode octets in URLs.
     */
    private static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * Decodes the specified URL as per RFC 3986, i.e. transforms
     * percent-encoded octets to characters by decoding with the UTF-8 character
     * set. This function is primarily intended for usage with
     * {@link java.net.URL} which unfortunately does not enforce proper URLs. As
     * such, this method will leniently accept invalid characters or malformed
     * percent-encoded octets and simply pass them literally through to the
     * result string. Except for rare edge cases, this will make unencoded URLs
     * pass through unaltered.
     *
     * @param url  The URL to decode, may be <code>null</code>.
     * @return The decoded URL or <code>null</code> if the input was
     *         <code>null</code>.
     */
    static String decodeUrl(String url) {
        String decoded = url;
        if (url != null && url.indexOf('%') >= 0) {
            int n = url.length();
            StringBuffer buffer = new StringBuffer();
            ByteBuffer bytes = ByteBuffer.allocate(n);
            for (int i = 0; i < n;) {
                if (url.charAt(i) == '%') {
                    try {
                        do {
                            byte octet = (byte) Integer.parseInt(
                                    url.substring(i + 1, i + 3), 16);
                            bytes.put(octet);
                            i += 3;
                        } while (i < n && url.charAt(i) == '%');
                        continue;
                    } catch (RuntimeException e) {
                        // malformed percent-encoded octet, fall through and
                        // append characters literally
                    } finally {
                        if (bytes.position() > 0) {
                            bytes.flip();
                            buffer.append(UTF8.decode(bytes).toString());
                            bytes.clear();
                        }
                    }
                }
                buffer.append(url.charAt(i++));
            }
            decoded = buffer.toString();
        }
        return decoded;
    }
}

Related

  1. decode(String url)
  2. decode(String url)
  3. decodeURL(String value)
  4. decodeUri(Context ctx, Uri selectedImage)