简体   繁体   English

从百分比编码的URL中提取十六进制值

[英]Extract hexadecimal values from a percent encoded URL

Let's say for example i have URL containing the following percent encoded character : %80 举例来说,假设我的网址包含以下百分比编码字符:%80
It is obviously not an ascii character. 显然这不是ASCII字符。
How would it be possible to convert this value to the corresponding hex string in Java. 如何在Java中将此值转换为相应的十六进制字符串。 i tried the following with no luck.Result should be 80. 我没有运气尝试了以下结果应该是80。

    public static void main(String[] args) {
        System.out.print(byteArrayToHexString(URLDecoder.decode("%80","UTF-8").getBytes()));
    }
    public static String byteArrayToHexString(byte[] bytes)
    {
      StringBuffer buffer = new StringBuffer();
      for(int i=0; i<bytes.length; i++)
      {
        if(((int)bytes[i] & 0xff) < 0x10)
        buffer.append("0");
        buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
      }
      return buffer.toString();
  }

The best way to deal with this is to parse the url using either java.net.URL or java.net.URI , and then use the relevant getters to extract the components that you require. 解决此问题的最佳方法是使用java.net.URLjava.net.URI解析URL,然后使用相关的getter提取所需的组件。 These will take care of decoding any %-encoded portions in the appropriate fashion. 这些将负责以适当的方式解码任何%编码的部分。

The problem with your current idea is that %80 does not represent "80" , or 80 . 您当前想法的问题是%80不代表"80"80 Rather it represents a byte that further needs to be interpreted in the context of the character encoding of the URL. 相反,它表示一个字节,需要在URL的字符编码的上下文中进一步解释该字节。 And if the encoding is UTF-8, then the %80 needs to be followed by one or two more %-encoded bytes ... otherwise this is a malformed UTF-8 character representation. 并且,如果编码为UTF-8,则%80之后必须再加上一个或两个%编码的字节...否则,这是格式错误的UTF-8字符表示形式。

I don't really see what you are trying. 我真的看不到你在想什么。 However, I'll give it a try. 但是,我会尝试一下。

  • When you have got this String: "%80" and you want to got the string "80" , you can use this: 当您获得以下字符串: "%80"并想要获得字符串 "80" ,可以使用以下命令:

     String str = "%80"; String hex = str.substring(1); // Cut off the '%' 
  • If you are trying to extract the value 0x80 (which is 128 in decimal) out of it: 如果您尝试从中提取 0x80 (十进制为128 ):

     String str = "%80"; String hex = str.substring(1); // Cut off the '%' int value = Integer.parseInt(hex, 16); 
  • If you are trying to convert an int to its hexadecimal representation use this: 如果您尝试将int转换为其十六进制表示形式,请使用以下命令:

     String hexRepresenation = Integer.toString(value, 16); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM