BASE64的编码URL传输问题,附十六进制编码字符。

程序引用了apache的jar包,版本:commons-codec-1.6.jar

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class Base64UtilDemo {


    public static void main(String[] args) throws UnsupportedEncodingException {
 
        String s=Base64.encodeBase64URLSafeString("中文那 instead o".getBytes("utf-8"));
        System.out.println(s);
        byte[] btye=Base64.decodeBase64(s);
        System.out.println(new String(btye,"utf-8"));
        String s2=Base64.encodeBase64String("中文那 instead o".getBytes("utf-8"));
        System.out.println(s2);
        byte[] btye2=Base64.decodeBase64(s2);
        System.out.println(new String(btye2,"utf-8"));
        
        String hexStr=byte2HexStr("中文那 instead o".getBytes("utf-8"));
        System.out.println(hexStr);
        byte[] btye3=hexStr2Bytes(hexStr);
        System.out.println(new String(btye3,"utf-8"));
    }

    
    /**
     * bytes转换成十六进制字符串
     */
    public static String byte2HexStr(byte[] b) {
        String hs="";
        String stmp="";
        for (int n=0;n<b.length;n++) {
            stmp=(Integer.toHexString(b[n] & 0XFF));
            if (stmp.length()==1) hs=hs+"0"+stmp;
            else hs=hs+stmp;
            //if (n<b.length-1)  hs=hs+":";
        }
        return hs.toUpperCase();
    }
   
    private static byte uniteBytes(String src0, String src1) {
        byte b0 = Byte.decode("0x" + src0).byteValue();
        b0 = (byte) (b0 << 4);
        byte b1 = Byte.decode("0x" + src1).byteValue();
        byte ret = (byte) (b0 | b1);
        return ret;
    }
   
    /**
     * bytes转换成十六进制字符串
     */
    public static byte[] hexStr2Bytes(String src) {
        int m=0,n=0;
        int l=src.length()/2;
//        System.out.println(l);
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            m=i*2+1;
            n=m+1;
            ret[i] = uniteBytes(src.substring(i*2, m),src.substring(m,n));
        }
        return ret;
    }

}


输出结果为:

5Lit5paH6YKjIGluc3RlYWQgbw
中文那 instead o
5Lit5paH6YKjIGluc3RlYWQgbw==
中文那 instead o
E4B8ADE69687E982A320696E7374656164206F
中文那 instead o


注意问题:

1.Base64编码比十六进制字符编码高效,十六进制编码是天然支持URL传输。

2.旧版Base64编码含有URL不安全字符,所以没办法直接使用。

3.新的Base64已经有支持URL了,但是解码方法跟旧的是同一个Base64.decodeBase64。

4.有的人喜欢自己处理旧版Base64的问题,比如用URLEncoder.encode,这样要分情况处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值