123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- /*
- * urlencode.cpp
- *
- * Created on: 2022年6月1日
- * Author: dingxy
- */
- #include "urlencode.h"
- #include "assert.h"
- unsigned char toHex(unsigned char c) {
- return c > 9? 'A'-10+c : '0'+c;
- }
-
- unsigned char fromHex(unsigned char h) {
- unsigned char c = 0;
- if(h>='A' && h<='Z') {
- c = h-'A'+10;
- }else if(h>='a' && h<='z') {
- c = h-'a'+10;
- } else if(h>='0' && h<='9') {
- c = h-'0';
- } else {
- }
- return c;
- }
-
- void encodeUrl(const string& str, string& result) {
- int len = str.length();
- for(int i=0; i<len; i++) {
- if(isalnum((unsigned char)str[i]) ||
- (str[i]=='.')||(str[i]=='-')||(str[i]=='*')||(str[i]=='_')) {
- result += str[i];
- } else if(str[i] == ' ') {
- result += '+';
- } else {
- result += '%';
- result += toHex((unsigned char)str[i] >> 4);
- result += toHex((unsigned char)str[i] & 0xF);
- }
- }
- }
-
- void encodeUrl(const char* str, string &result) {
- string tmp = str;
- encodeUrl(tmp, result);
- }
-
- void decodeUrl(const string& str, string &result) {
- result = "";
- int len = str.length();
- for(int i=0; i<len; i++) {
- if((str[i]=='.')||(str[i]=='-')||(str[i]=='*')||(str[i]=='_')) {
- result += str[i];
- } else if(str[i] == '+') {
- result += ' ';
- } else if(str[i] == '%') {
- assert(i+2 < len);
- unsigned char high = fromHex((unsigned char)str[++i]);
- unsigned char low = fromHex((unsigned char)str[++i]);
- result += ((high<<4) | low);
- } else if(isalnum((unsigned char)str[i])){
- result += str[i];
- } else {
- }
- }
- }
-
- void decodeUrl(const char* str, string &result) {
- string tmp = str;
- decodeUrl(tmp, result);
- }
|