Java URLDecoder和URLEncoder對中文進行編碼和解碼

  • URLDecoder類包含一個decode(String s,String enc)靜態方法,它能夠將application/x-www-form-urlencoded MIME字符串轉成普通字符串;java

  • URLEncoder類包含一個encode(String s,String enc)靜態方法,它能夠將普通字符串轉換成application/x-www-form-urlencoded MIME字符串。app

    package com.test;
    import com.sun.deploy.net.URLEncoder;
    import java.net.URLDecoder;
    public class JunitTestURLcode {
        @Test
        public void testURLcode()throws Exception{
            //將application/x-www-form-urlencoded字符串轉換成普通字符串
            //採用UTF-8字符集進行解碼
            System.out.println(URLDecoder.decode("%E5%8C%97%E4%BA%AC%E5%A4%A7%E5%AD%A6", "UTF-8"));
            //採用GBK字符集進行解碼
            System.out.println(URLDecoder.decode("%B1%B1%BE%A9%B4%F3%D1%A7", "GBK"));
    
            // 將普通字符串轉換成application/x-www-form-urlencoded字符串
            //採用utf-8字符集
            System.out.println(URLEncoder.encode("北京大學", "UTF-8"));
            //採用GBK字符集
            System.out.println(URLEncoder.encode("北京大學", "GBK"));
        }
    
    }
相關文章
相關標籤/搜索