Here you can find the source of encode(String s, String enc)
Encode a given string.
Parameter | Description |
---|---|
s | String to encode. |
enc | Encode. |
Parameter | Description |
---|---|
IllegalArgumentException | If string is empty or null. |
public static String encode(String s, String enc)
//package com.java2s; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; public class Main { /**/* w w w .j ava2 s. c o m*/ * <p> * Encode a given string. If encode type is not informed, UTF-8 is * considered. * </p> * @param s String to encode. * @param enc Encode. * @return Encoded string. * @throws IllegalArgumentException If string is empty or null. */ public static String encode(String s, String enc) { if (s == null) { throw new IllegalArgumentException("String must not be null"); } if (enc == null) { enc = "UTF-8"; } // ByteArrayInputStream bIn; // try { bIn = new ByteArrayInputStream(s.getBytes(enc)); } catch (UnsupportedEncodingException e) { bIn = new ByteArrayInputStream(s.getBytes()); } // int c = bIn.read(); StringBuffer ret = new StringBuffer(); // while (c >= 0) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_') { ret.append((char) c); } else if (c == ' ') { ret.append("%20"); } else { if (c < 128) { ret.append(getHexChar(c)); } else if (c < 224) { ret.append(getHexChar(c)); ret.append(getHexChar(bIn.read())); } else if (c < 240) { ret.append(getHexChar(c)); ret.append(getHexChar(bIn.read())); ret.append(getHexChar(bIn.read())); } } // c = bIn.read(); } // return ret.toString(); } /** * <p> * Get a hex value of a char. * </p> * @param c Char. */ private static String getHexChar(int c) { return (c < 16 ? "%0" : "%") + Integer.toHexString(c).toUpperCase(); } }