Java URL Encode encodeURLComponent(final String s)

Here you can find the source of encodeURLComponent(final String s)

Description

encode URL Component

License

Open Source License

Declaration

public static String encodeURLComponent(final String s) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;

import java.util.Locale;

public class Main {
    public static String encodeURLComponent(final String s) {
        if (s == null) {
            return "";
        }//from   w w  w  . j a va 2  s  . c om

        final StringBuilder sb = new StringBuilder();

        try {
            for (int i = 0; i < s.length(); i++) {
                final char c = s.charAt(i);

                if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'))
                        || (c == '-') || (c == '.') || (c == '_') || (c == '~')) {
                    sb.append(c);
                } else {
                    final byte[] bytes = ("" + c).getBytes("UTF-8");

                    for (byte b : bytes) {
                        sb.append('%');

                        int upper = (((int) b) >> 4) & 0xf;
                        sb.append(Integer.toHexString(upper).toUpperCase(Locale.US));

                        int lower = ((int) b) & 0xf;
                        sb.append(Integer.toHexString(lower).toUpperCase(Locale.US));
                    }
                }
            }

            return sb.toString();
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("UTF-8 unsupported!?", uee);
        }
    }
}

Related

  1. encodeURL(BitSet urlsafe, byte[] bytes)
  2. encodeUrl(final String input)
  3. encodeURL(String s)
  4. encodeURL(String s)
  5. encodeUrl(String url, String encoding)
  6. encodeUrlPath(String pathSegment)
  7. unpaddedBase64UrlEncoded(final String unencodedString)
  8. uriDecode(String src)
  9. uriDecode(String uri)