url編碼

	以下是url中可能用到的特殊字符及在url中的經過編碼後的值:
	
	特殊字符的含義
	URL編碼
	
	#           用來標誌特定的文檔位置   %23
	
	%         對特殊字符進行編碼            %25
	
	&         分隔不同的變量值對             %26
	
	+         在變量值中表示空格             %2B
	
	/          表示目錄路徑                          %2F
	
	\          表示目錄路徑                          %5C
	
	=         用來連接鍵和值                      %3D
	
	?         表示查詢字符串的開始          %3F
	
	空格    空格                                         %20
	
	.          句號                                          %2E
	
	:         冒號                                           %3A
	
	但上面並不是一個特殊的映射集,%編碼是有特點的規則的:

url編碼,只是將串的內存數據按字節用16進製表示,

在這裏插入圖片描述

由上可知,數字,字母,’.’ 是不進行url編碼的。

下爲源碼,接好(如有不當,聯繫我)

#include<string>
#include<iostream>
using namespace std;

char dec2hexChar(short int n) {
	if (0 <= n && n <= 9) {
		return char(short('0') + n);
	}
	else if (10 <= n && n <= 15) {
		return char(short('A') + n - 10);
	}
	else
		throw "except occurred";
}

short int hexChar2dec(char c) {
	if ('0' <= c && c <= '9') {
		return short(c - '0');
	}
	else if ('a' <= c && c <= 'f') {
		return (short(c - 'a') + 10);
	}
	else if ('A' <= c && c <= 'F') {
		return (short(c - 'A') + 10);
	}
	else
		throw "except";
}

string escapeURL(const string &URL)
{
	string result = "";
	for (unsigned int i = 0; i<URL.size(); i++) {
		char c = URL[i];
		if (
			('0' <= c && c <= '9') ||
			('a' <= c && c <= 'z') ||
			('A' <= c && c <= 'Z') ||
			 c == '.') {
			result += c;
		}
		else {
			int j = (short int)c;
			if (j < 0) {
				j += 256;
			}
			int i1, i0;
			i1 = j / 16;
			i0 = j - i1 * 16;
			result += '%';
			result += dec2hexChar(i1);
			result += dec2hexChar(i0);
		}
	}
	return result;
}

string deescapeURL(const string &URL) {
	string result = "";
	for (unsigned int i = 0; i<URL.size(); i++) {
		char c = URL[i];
		if (c != '%') {
			result += c;
		}
		else {
			char c1 = URL[++i];
			char c0 = URL[++i];
			int num = 0;
			num += hexChar2dec(c1) * 16 + hexChar2dec(c0);
			result += char(num);
		}
	}
	return result;
}

int main()
{
	string str = "歲月123abc.#";
	string temp = escapeURL(str);
	std::cout<<temp << endl;
	std::cout << deescapeURL(temp) << endl;
	getchar();
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章