java 中实现类似js encodeURIComponent 函数
创始人
2024-11-16 10:22:30
0次
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
 
/**
 * Utility class for JavaScript compatible UTF-8 encoding and decoding.
 * 
 * @see http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output
 * @author John Topley 
 */
public class EncodingUtil {
 /**
  * Decodes the passed UTF-8 String using an algorithm that's compatible with
  * JavaScript's decodeURIComponent function. Returns
  * null if the String is null.
  *
  * @param s The UTF-8 encoded String to be decoded
  * @return the decoded String
  */
 public static String decodeURIComponent(String s) {
  if (s == null) {
   return null;
  }
 
  String result = null;
 
  try {
   result = URLDecoder.decode(s, "UTF-8");
  }
 
  // This exception should never occur.
  catch (UnsupportedEncodingException e) {
   result = s; 
  }
 
  return result;
 }
 
 /**
  * Encodes the passed String as UTF-8 using an algorithm that's compatible
  * with JavaScript's encodeURIComponent function. Returns
  * null if the String is null.
  * 
  * @param s The String to be encoded
  * @return the encoded String
  */
 public static String encodeURIComponent(String s) {
  String result = null;
 
  try {
   result = URLEncoder.encode(s, "UTF-8")
             .replaceAll("\\+", "%20")
             .replaceAll("\\%21", "!")
             .replaceAll("\\%27", "'")
             .replaceAll("\\%28", "(")
             .replaceAll("\\%29", ")")
             .replaceAll("\\%7E", "~");
  }
 
  // This exception should never occur.
  catch (UnsupportedEncodingException e) {
   result = s;
  }
 
  return result;
 } 
 
 /**
  * Private constructor to prevent this class from being instantiated.
  */
 private EncodingUtil() {
  super();
 }
}

补充知识:java 代码实现encodeURIComponent和decodeURIComponent,解决空格转义为加号的问题

java自带有一个 java.net.URLDecoder和java.net.URLEncoder。

通过这两个类,可以调用encode()或者decode()方法对字符串进行URL编码。

那既然有了,为什么还要自己实现一套呢?主要原因是Jdk中并没有提供encodeURIComponent和decodeURIComponent的方法。

这两个方法作用其实跟encode()和decode()基本相似。区别主要是,在java中,url编码时,会把空格转换成+号。而某些非java语言实现的客户端一般空格转义出来是 %20 ,这样就容易发生decode不出这个空格的问题。比如IOS中,会把这个+直接显示了,而不是转义成空格。这就跟我们想要的结果违背了。比如js中就自带有encodeURIComponent和decodeURIComponent的方法。

java我们就自己实现一下吧。直接看代码,一看就明白。

/*
 * 文件名:URIEncode.java 描述: 修改人:gogym 修改时间:2018年11月16日 跟踪单号: 修改单号: 修改内容:
 */ 
 
import java.io.UnsupportedEncodingException; 
public class URIEncoder
{ 
  public static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";
 
  /**
   * Description:
   * 
   * @param str
   * @return
   * @throws UnsupportedEncodingException
   * @see
   */
  public static String encodeURI(String str)
    throws UnsupportedEncodingException
  {
    String isoStr = new String(str.getBytes("UTF8"), "ISO-8859-1");
    char[] chars = isoStr.toCharArray();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < chars.length; i++ )
    {
      if ((chars[i] <= 'z' && chars[i] >= 'a') || (chars[i] <= 'Z' && chars[i] >= 'A')
        || chars[i] == '-' || chars[i] == '_' || chars[i] == '.' || chars[i] == '!'
        || chars[i] == '~' || chars[i] == '*' || chars[i] == '\'' || chars[i] == '('
        || chars[i] == ')' || chars[i] == ';' || chars[i] == '/' || chars[i] == '?'
        || chars[i] == ':' || chars[i] == '@' || chars[i] == '&' || chars[i] == '='
        || chars[i] == '+' || chars[i] == '$' || chars[i] == ',' || chars[i] == '#'
        || (chars[i] <= '9' && chars[i] >= '0'))
      {
        sb.append(chars[i]);
      }
      else
      {
        sb.append("%");
        sb.append(Integer.toHexString(chars[i]));
      }
    }
    return sb.toString();
  }
 
  /**
   * Description:
   * 
   * @param input
   * @return
   * @see
   */
  public static String encodeURIComponent(String input)
  {
    if (null == input || "".equals(input.trim()))
    {
      return input;
    }
 
    int l = input.length();
    StringBuilder o = new StringBuilder(l * 3);
    try
    {
      for (int i = 0; i < l; i++ )
      {
        String e = input.substring(i, i + 1);
        if (ALLOWED_CHARS.indexOf(e) == -1)
        {
          byte[] b = e.getBytes("utf-8");
          o.append(getHex(b));
          continue;
        }
        o.append(e);
      }
      return o.toString();
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    return input;
  }
 
  private static String getHex(byte buf[])
  {
    StringBuilder o = new StringBuilder(buf.length * 3);
    for (int i = 0; i < buf.length; i++ )
    {
      int n = (int)buf[i] & 0xff;
      o.append("%");
      if (n < 0x10)
      {
        o.append("0");
      }
      o.append(Long.toString(n, 16).toUpperCase());
    }
    return o.toString();
  }
}
/*
 * 文件名:URIDecode.java 描述: 修改人:gogym 修改时间:2018年11月16日 跟踪单号: 修改单号: 修改内容:
 */
 
package com.poly.rbl.plugin.uri; 
public class URIDecoder
{ 
  /**
   * 
   * Description: 
   * 
   * @param encodedURI
   * @return 
   * @see
   */
  public static String decodeURIComponent(String encodedURI)
  {
    char actualChar;
 
    StringBuffer buffer = new StringBuffer();
 
    int bytePattern, sumb = 0;
 
    for (int i = 0, more = -1; i < encodedURI.length(); i++ )
    {
      actualChar = encodedURI.charAt(i);
 
      switch (actualChar)
      {
        case '%':
        {
          actualChar = encodedURI.charAt(++i);
          int hb = (Character.isDigit(actualChar) ? actualChar - '0' : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
          actualChar = encodedURI.charAt(++i);
          int lb = (Character.isDigit(actualChar) ? actualChar - '0' : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
          bytePattern = (hb << 4) | lb;
          break;
        }
        case '+':
        {
          bytePattern = ' ';
          break;
        }
        default:
        {
          bytePattern = actualChar;
        }
      }
 
      if ((bytePattern & 0xc0) == 0x80)
      { // 10xxxxxx
        sumb = (sumb << 6) | (bytePattern & 0x3f);
        if (--more == 0) buffer.append((char)sumb);
      }
      else if ((bytePattern & 0x80) == 0x00)
      { // 0xxxxxxx
        buffer.append((char)bytePattern);
      }
      else if ((bytePattern & 0xe0) == 0xc0)
      { // 110xxxxx
        sumb = bytePattern & 0x1f;
        more = 1;
      }
      else if ((bytePattern & 0xf0) == 0xe0)
      { // 1110xxxx
        sumb = bytePattern & 0x0f;
        more = 2;
      }
      else if ((bytePattern & 0xf8) == 0xf0)
      { // 11110xxx
        sumb = bytePattern & 0x07;
        more = 3;
      }
      else if ((bytePattern & 0xfc) == 0xf8)
      { // 111110xx
        sumb = bytePattern & 0x03;
        more = 4;
      }
      else
      { // 1111110x
        sumb = bytePattern & 0x01;
        more = 5;
      }
    }
    return buffer.toString();
  }
}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...