Java String Encode encode(String s, String encoding)

Here you can find the source of encode(String s, String encoding)

Description

encode

License

Open Source License

Declaration

public static String encode(String s, String encoding) throws UnsupportedEncodingException 

Method Source Code


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

import java.io.UnsupportedEncodingException;

public class Main {
    private static final String hex = "0123456789ABCDEF";

    public static String encode(String s, String encoding) throws UnsupportedEncodingException {
        int length = s.length();
        int start = 0;
        int i = 0;
        StringBuilder result = new StringBuilder(length);
        while (true) {
            while ((i < length) && isSafe(s.charAt(i))) {
                i++;/*  ww w . ja v  a 2s  .c o m*/
            }
            result.append(s.substring(start, i));
            if (i >= length) {
                return result.toString();
            } else if (s.charAt(i) == ' ') {
                result.append('+');
                i++;
            } else {
                start = i;
                char c;
                while ((i < length) && ((c = s.charAt(i)) != ' ') && !isSafe(c)) {
                    i++;
                }
                String unsafe = s.substring(start, i);
                byte[] bytes = unsafe.getBytes(encoding);
                for (int j = 0; j < bytes.length; j++) {
                    result.append('%');
                    int val = bytes[j];
                    result.append(hex.charAt((val & 0xf0) >> 4));
                    result.append(hex.charAt(val & 0x0f));
                }
            }
            start = i;
        }
    }

    private static boolean isSafe(char c) {
        return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || (c == '-')
                || (c == '_') || (c == '.') || (c == '*'));
    }
}

Related

  1. encode(String name)
  2. encode(String s)
  3. encode(String s)
  4. encode(String s)
  5. encode(String s, String enc)
  6. encode(String source, String charsetFrom, String charsetTo)
  7. encode(String src)
  8. encode(String src, String charset)
  9. encode(String str)