`

URL的编码和解码

    博客分类:
  • Java
阅读更多
首先,要对URL进行编码和解码,需要导入Commons codec的jar包。
这是Commons项目中用来处理常用的编码方法的工具类包,例如DES、SHA1、MD5、Base64,URL,Soundx等等。
1.Pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>EncryptUrl</groupId>
    <artifactId>EncryptUrl</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--Commons-codec-->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.6</version>
        </dependency>
    </dependencies>

</project>
 2.Java代码
import org.apache.commons.codec.binary  .Base64;

import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA..
 * User: Leon
 * Date: 14-2-17
 * Time: 上午10:18
 * To change this template use File | Settings | File Templates.
 */
public class EncryptUrl {
    public static final String ENCODING = "UTF-8";
    public static String close(String url){

        byte[] b;
        String close = null;
        try {
            b = Base64.encodeBase64URLSafe(url.getBytes(ENCODING));
            close = new String(b, ENCODING);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return close;
    }

    public static String open(String close){

        byte[] b;
        String open = null;
        try {
            b = Base64.decodeBase64(close.getBytes(ENCODING));
            open = new String(b,ENCODING);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return open;

    }

    public static void main(String[] args) {

        String msg = "http://www.baidu.com";
        System.out.println("加密前:"+msg);
        String close = close(msg);
        System.out.println("加密后:"+close);
        String open = open(close);
        System.out.println("解密后;"+open);
        System.out.println(open("YXBpL3YyL2dvb2RzL2JyYW5kX2xpc3Q_YnJhbmRfaWQ9MzAy"));

        open = open("YXBpL3YyL2dvb2RzL2JyYW5kX2xpc3Q_YnJhbmRfaWQ9MzAy");
        for(int i=0; i<4; i++){
            System.out.println(i+"---"+open);
            open = open(open);
        }

        System.out.println(close("example00/v2/goods/brand_list?brand_id=302"));


        System.out.println(close("example00/v2/goods/brand_list?brand_id=302&page=1"));

        open = "YXBpL3YxL2dvb2RzL2NhdGVnb3J5X3BhcmVudF9saXN0P2NoaWxkX2lkPTM1";
        open = "YXBpL3YyL2dvb2RzL2JyYW5kX2xpc3Q_YnJhbmRfaWQ9MzA2";
        System.out.println("--"+open(open));

    }
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics