一、需要的官方类
JDK默认有下列类:
数学函数类: java.lang.Math
URL解码类: java.net.URLDecoder
URL编码类: java.net.URLEncoder
Base64编码类: java.util.Base64
二、测试类如下:
import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Base64; /** * @author * @version 1.0.0 * <p> * date: 2026/1/1 **/ public class UtilTest { public static void main(String[] args) { System.out.println("计算二分之PI的正弦函数:" + Math.sin(Math.PI / 2)); System.out.println("获得随机小数:" + Math.random()); System.out.println("------- URL编码测试 ------"); String url = "name=小明&sex=男"; String str = ""; try { // 参数依次是Unicode字符、字符集编码 // 返回:编码结果 str = URLEncoder.encode(url, "UTF-8"); System.out.println("URL编码结果:" + str); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("------- URL解码测试 ----"); try { // 参数依次是URL编码字符、字符集编码 // 返回:解码结果 System.out.println("URL解码结果:" + URLDecoder.decode(str, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("------- Base64编码 -----"); String raw = "我是中国人"; try { // 传入字符串的字节序列,返回base64字符串 String base64 = Base64.getEncoder().encodeToString(raw.getBytes("UTF-8")); System.out.println("base64:" + base64); // decode(base64字符串)返回是字节序列,用String构造方法转成字符串。 // 转成字符串的字符集是UTF-8,要编码和解码字符集一致 System.out.println("原始:" + new String(Base64.getDecoder().decode(base64), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }三、执行结果
结果基本正确。