1. 程式人生 > >處理URL編碼與解碼

處理URL編碼與解碼

Python

url編碼:

urllib.quote(url)#沒有對“/”進行處理
urllib.quote_plus(url)

url解碼:

urllib.unquote(url)#沒有對“/”進行處理
urllib.unquote_plus(url)

完整示例:

#coding=utf-8
import urllib
url = 'http://www.xxx.com/?name=老王'
encoded_url=urllib.quote_plus(url)
print encoded_url
print urllib.unquote_plus(encoded_url)

列印輸出:

http%3A%2F%2Fwww.xxx.com%2F%3Fname%3D%E8%80%81%E7%8E%8B
http://www.xxx.com/?name=老王

JS

url編碼:

encodeURI(url);//只對中文處理,其他字元不處理
encodeURIComponent(url);

url解碼:

decodeURI(url);//只對中文處理,其他字元不處理
decodeURIComponent(url);

完整示例:

<script>
var url = "http://www.xxx.com/?name=老王";
var encoded_url=encodeURIComponent
(url) alert(encoded_url); alert(decodeURIComponent(encoded_url)); <script>

列印輸出:

http%3A%2F%2Fwww.xxx.com%2F%3Fname%3D%E8%80%81%E7%8E%8B
http://www.xxx.com/?name=老王

Java

url編碼:

java.net.URLEncoder.encode(url);//已過時,其實可以用
java.net.URLEncoder.encode(url,"UTF-8");//第二個引數"UTF-8"是表示使用什麼編碼對url進行編碼,即該方法返回的是什麼編碼的url

url解碼:

java.net.URLDecoder.decode(url);//已過時,其實可以用
java.net.URLDecoder.decode(url,"UTF-8");//第二個引數"UTF-8"是表示使用什麼編碼對url進行解碼,即該方法傳入的是什麼編碼的url

完整示例:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class UrlCodingTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "http://www.xxx.com/?name=老王";
        String encoded_url = URLEncoder.encode(url,"UTF-8");
        System.out.println(encoded_url);
        System.out.println(URLDecoder.decode(encoded_url,"UTF-8"));
    }
}

列印輸出:

http%3A%2F%2Fwww.xxx.com%2F%3Fname%3D%E8%80%81%E7%8E%8B
http://www.xxx.com/?name=老王

PHP

url編碼:

urlencode("http://www.baidu.com/?name=唐朝&sex=男");

url解碼:

urldecode("http%3A%2F%2Fwww.baidu.com%2F%3Fname%3D%E5%94%90%E6%9C%9D%26sex%3D%E7%94%B7");