Java URL Encode uriDecode(String src)

Here you can find the source of uriDecode(String src)

Description

uri Decode

License

Open Source License

Declaration

public static String uriDecode(String src) 

Method Source Code


//package com.java2s;
/*/*from ww w . java 2 s.c  o  m*/
 * ====================================================================
 * Copyright (c) 2004-2012 TMate Software Ltd.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://svnkit.com/license.html
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 * ====================================================================
 */

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

public class Main {
    public static String uriDecode(String src) {
        // this is string in ASCII-US encoding.
        boolean query = false;
        boolean decoded = false;
        int length = src.length();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
        for (int i = 0; i < length; i++) {
            byte ch = (byte) src.charAt(i);
            if (ch == '?') {
                query = true;
            } else if (ch == '+' && query) {
                ch = ' ';
            } else if (ch == '%' && i + 2 < length && isHexDigit(src.charAt(i + 1))
                    && isHexDigit(src.charAt(i + 2))) {
                ch = (byte) (hexValue(src.charAt(i + 1)) * 0x10 + hexValue(src.charAt(i + 2)));
                decoded = true;
                i += 2;
            } else {
                // if character is not URI-safe try to encode it.
            }
            bos.write(ch);
        }
        if (!decoded) {
            return src;
        }
        try {
            return new String(bos.toByteArray(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return src;
    }

    public static boolean isHexDigit(char ch) {
        return Character.isDigit(ch) || (Character.toUpperCase(ch) >= 'A' && Character.toUpperCase(ch) <= 'F');
    }

    private static int hexValue(char ch) {
        if (Character.isDigit(ch)) {
            return ch - '0';
        }
        ch = Character.toUpperCase(ch);
        return (ch - 'A') + 0x0A;
    }
}

Related

  1. encodeURL(String s)
  2. encodeUrl(String url, String encoding)
  3. encodeURLComponent(final String s)
  4. encodeUrlPath(String pathSegment)
  5. unpaddedBase64UrlEncoded(final String unencodedString)
  6. uriDecode(String uri)
  7. uriEncode(String uriRef)
  8. URLEncode(byte[] input)
  9. urlEncode(byte[] rs)