如何从十六进制编码的字符串解码为UTF-8字符串

How to decode to UTF-8 String from Hex encoded string

本文关键字:字符串 解码 UTF-8 编码 十六进制      更新时间:2023-09-26

我得到HTML Javascript字符串,例如:

htmlString = "https'x3a'x2f'x2ftest.com"

但我想解码如下:

str = "https://test.com"

也就是说,我想要一个Util API,比如:

 public static String decodeHex(String htmlString){
   // do decode and converter here 
 }
 public static void main(String ...args){
       String htmlString = "https'x3a'x2f'x2ftest.com";
       String str = decodeHex(htmlString);
       // str should be "https://test.com"
 }

有人知道如何实现这个API-decodeHex吗?

这应该足以让您开始。我把实现hexDecode和整理格式错误的输入作为一个练习留给您。

public String decode(String encoded) {
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < encoded.length(); i++) {
    if (encoded.charAt(i) == ''' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
      sb.append(hexDecode(encoded.substring(i + 2, i + 4)));
      i += 3;
    } else {
      sb.append(encoded.charAt(i));
    }
  }
  return sb.toString;
}
public String decode(String encoded) throws DecoderException {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < encoded.length(); i++) {
        if (encoded.charAt(i) == '''' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
          sb.append(new String(Hex.decodeHex(encoded.substring(i + 2, i + 4).toCharArray()),StandardCharsets.UTF_8));
          i += 3;
        } else {
          sb.append(encoded.charAt(i));
        }
      }
      return sb.toString();
    }