URL编码/解码工具

常见问题

什么是 URL 编码?

URL 编码是一种将字符转换为可以通过互联网传输的格式的方法。URL 只能使用 ASCII 字符集通过互联网发送。由于 URL 经常包含 ASCII 集之外的字符,因此需要转换 URL。URL 编码将不安全的 ASCII 字符替换为 '%' 后跟两个十六进制数字。

URL 编码如何工作?

URL 编码通过将不安全字符替换为 '%' 后跟表示该字符 UTF-8 编码的两个十六进制数字来工作。例如,空格字符编码为 %20。URL 不能包含空格,因此它们被替换为加号 (+) 或 %20。其他特殊字符则被替换为对应的 %xx 代码。

常见需要 URL 编码的字符

以下是在 URL 中使用时需要 URL 编码的常见字符:

字符URL编码说明
Space%20URL中最常见的需要编码的字符
!%21感叹号
"%22双引号
#%23哈希符号(用于URL片段)
$%24美元符号
%%25百分号(URL编码的转义字符)
&%26与符号(URL参数分隔符)
'%27单引号
(%28左括号
)%29右括号
+%2B加号
,%2C逗号
/%2F斜杠(URL路径分隔符)
=%3D等号(URL参数赋值符号)
?%3F问号(URL查询字符串开始符号)

不同编程语言中的 URL 编码实现

以下是各种编程语言中 URL 编码和解码的示例:

Go

package main

import (
    "fmt"
    "net/url"
)

func main() {
    // Encode a URL
    text := "Hello World! Special chars: &?=/";
    encoded := url.QueryEscape(text)
    fmt.Println("Encoded:", encoded)

    // Decode a URL
    decoded, err := url.QueryUnescape(encoded)
    if err == nil {
        fmt.Println("Decoded:", decoded)
    }
}

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// Function to URL-encode a string
char *url_encode(char *str) {
    char *encoded = malloc(strlen(str) * 3 + 1);
    char *pstr = str;
    char *pbuf = encoded;

    while (*pstr) {
        if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') {
            *pbuf++ = *pstr;
        } else if (*pstr == ' ') {
            *pbuf++ = '+';
        } else {
            sprintf(pbuf, "%%%.2X", *pstr);
            pbuf += 3;
        }
        pstr++;
    }
    *pbuf = '\\0';

    return encoded;
}

int main() {
    char *text = "Hello World! Special chars: &?=/";
    char *encoded = url_encode(text);

    printf("Original: %s\\n", text);
    printf("Encoded: %s\\n", encoded);

    free(encoded);
    return 0;
}

PHP

<?php
// URL encoding
$text = "Hello World! Special chars: &?=/";
$encoded = urlencode($text);
echo "Encoded: " . $encoded . "\\n";

// URL decoding
$decoded = urldecode($encoded);
echo "Decoded: " . $decoded . "\\n";
?>

Python

import urllib.parse

# URL encoding
text = "Hello World! Special chars: &?=/"
encoded = urllib.parse.quote(text)
print(f"Encoded: {encoded}")

# URL decoding
decoded = urllib.parse.unquote(encoded)
print(f"Decoded: {decoded}")

JavaScript

// URL encoding
const text = "Hello World! Special chars: &?=/";
const encoded = encodeURIComponent(text);
console.log("Encoded:", encoded);

// URL decoding
const decoded = decodeURIComponent(encoded);
console.log("Decoded:", decoded);

TypeScript

// URL encoding
const text: string = "Hello World! Special chars: &?=/";
const encoded: string = encodeURIComponent(text);
console.log("Encoded:", encoded);

// URL decoding
const decoded: string = decodeURIComponent(encoded);
console.log("Decoded:", decoded);

encodeURI 和 encodeURIComponent 有什么区别?

encodeURI() 适用于编码完整的 URI,因此不会对 URL 中具有特殊含义的字符进行编码,例如 /、?、:、@、&、=、+、$ 和 #。 相比之下,encodeURIComponent() 会对所有特殊字符进行编码,适用于对 URL 的部分内容进行编码,例如查询字符串参数。 在编码查询参数时,应始终使用 encodeURIComponent(),以确保所有特殊字符都被正确编码。