欢迎访问宙启技术站
智能推送

Java函数实现URL编码和解码的方法有哪些?

发布时间:2023-06-03 15:19:00

Java中提供了两种URL编码和解码的方法,分别是使用java.net包中的URLEncoder和URLDecoder类和使用java.nio.charset包中的StandardCharsets和CharsetEncoder和CharsetDecoder类。

一、使用java.net包中的URLEncoder和URLDecoder类

1. URLEncoder.encode(String s, String enc)

该方法用于将字符串s进行URL编码。参数enc指定了要使用的字符集,如果不指定,默认使用UTF-8字符集。该方法将s中所有不安全的字符转换成%XX类型格式,其中XX表示该字符的ASCII码值的16进制表示。不安全字符包括非ASCII编码字符、空格、加号、斜杠、问号等。该方法返回一个字符串,表示编码后的字符串。

2. URLDecoder.decode(String s, String enc)

该方法用于将URL编码的字符串s进行解码。参数enc指定了要使用的字符集,如果不指定,默认使用UTF-8字符集。该方法将s中所有%XX类型的字符都转换成该字符的ASCII码表示。该方法返回一个字符串,表示解码后的字符串。

使用示例:

String s = "Java函数实现URL编码和解码的方法有哪些?";
String encodeS = URLEncoder.encode(s, "UTF-8");
System.out.println(encodeS); //%4A%61%76%61%E5%87%BD%EF%BC%9A%E5%AE%9E%E7%8E%B0URL%E7%BC%96%E7%A0%81%E5%92%8C%E8%A7%A3%E7%A0%81%E7%9A%84%E6%96%B9%E6%B3%95%E6%9C%89%E5%93%AA%E4%BA%9B%EF%BC%9F
String decodeS = URLDecoder.decode(encodeS, "UTF-8");
System.out.println(decodeS); //Java函数实现URL编码和解码的方法有哪些?

二、使用java.nio.charset包中的StandardCharsets和CharsetEncoder和CharsetDecoder类

1. StandardCharsets

该类提供了Java支持的字符集类型的常量,例如UTF-8、ISO-8859-1、US-ASCII等。

2. CharsetEncoder和CharsetDecoder

这两个类用于将字符序列编码为字节序列或将字节序列解码为字符序列。其中,CharsetEncoder将字符序列编码为字节序列,使用方法为:

CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ByteBuffer buffer = encoder.encode(CharBuffer.wrap(s));
byte[] bytes = buffer.array();

其中,s表示要编码的字符串。通过调用StandardCharsets.UTF_8.newEncoder()方法获取到UTF-8字符集的编码器,然后调用encoder.encode()方法将字符串转换为ByteBuffer类型的字节序列,最后通过调用buffer.array()方法获取转换后的字节数组。

CharsetDecoder用于将字节序列解码为字符序列,使用方法为:

CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
CharBuffer buffer = decoder.decode(ByteBuffer.wrap(bytes));
String s = buffer.toString();

其中,bytes表示要解码的字节数组。通过调用StandardCharsets.UTF_8.newDecoder()方法获取到UTF-8字符集的解码器,然后调用decoder.decode()方法将字节数组转换为CharBuffer类型的字符序列,最后通过调用buffer.toString()方法获取转换后的字符串。

使用示例:

String s = "Java函数实现URL编码和解码的方法有哪些?";
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ByteBuffer buffer = encoder.encode(CharBuffer.wrap(s));
byte[] bytes = buffer.array();
System.out.println(Arrays.toString(bytes)); //[-26, -75, -94, 74, 97, 118, 97, -27, -120, -110, -26, -106, -105, -24, -81, -68, -17, -68, -124, 58, -31, -89, -71, -17, -68, -126, -27, -96, -127, -24, -72, -122, -27, -100, -118, -26, -106, -120, -26, -83, -114, -27, -111, -55, 63]
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(bytes));
String decodeS = charBuffer.toString();
System.out.println(decodeS); //Java函数实现URL编码和解码的方法有哪些?

综上所述,Java函数实现URL编码和解码的方法有URLEncoder和URLDecoder类、CharsetEncoder和CharsetDecoder类。两种方法均可实现Url编码和解码,开发者可以根据具体需求选择适合的方法。