URLEncoder和URLDecoder编码和解码

URLDecoder和URLEncoder它的作用主要是用于普通字符串和application/x-www-form-rulencoded MIME字符串之间的转换

URLDecoder类包含一个decode(String s,String charcter)静态方法,它可以将看上去乱码的特殊字符串转换成普通字符串
URLEncoder类包含一个encode(String s,String charcter)静态方法,它可以将普通字符串转换成application/x-www-form-urlencoded MIME字符串

//将application/x-www-form-urlencoded字符串转换成普通字符串
String keyWord = URLDecoder.decode("%CD%F8%C2%E7%CA%B1%BF%D5", "UTF-8");
//将普通字符串转换成application/x-www-form-urlencoded字符串
String urlStr = URLEncoder.encode("网络时空" , "UTF-8");

注:可根据需求指定字符集,我这里用的UTF-8
  1. 编码‘utf-8’


/**
 * 编码‘utf-8’
 * @param data 要编码的字符串
 * @return 编码后的字符串
 * @throws UnsupportedEncodingException 转码异常(必须捕获)
 */
public static String encode(String data) throws UnsupportedEncodingException {
    // 参数一:要编码的字符串 参数二:指定字符集
    data = URLEncoder.encode(data,"utf-8");
    return data;
}
  1. 解码‘utf-8’


/**
 * 解码‘utf-8’
 * @param data 要解码的字符串
 * @return 解码后的字符串
 * @throws UnsupportedEncodingException 转码异常(必须捕获)
 */
public static String decode(String data) throws UnsupportedEncodingException {
    // 参数一:要解码的字符串 参数二:指定字符集
    data = URLDecoder.decode(data,"utf-8");
    return data;
}

测试


// 测试
public static void main(String[] args) {
    try {
        // 进行编码
        String encode = URLEncoder.encode("中文");
        System.out.println(encode);
        // 进行解码
        String decode = URLEncoder.decode(encode);
        System.out.println(decode);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

i源

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值