Extract hexadecimal values from a percent encoded URL
-
06-04-2021 - |
Question
Let's say for example i have URL containing the following percent encoded character : %80
It is obviously not an ascii character.
How would it be possible to convert this value to the corresponding hex string in Java.
i tried the following with no luck.Result should be 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();
}
Solution
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. 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
. Rather it represents a byte that further needs to be interpreted in the context of the character encoding of the 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.
OTHER TIPS
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:String str = "%80"; String hex = str.substring(1); // Cut off the '%'
If you are trying to extract the value
0x80
(which is128
in decimal) out of it: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:
String hexRepresenation = Integer.toString(value, 16);