A url like http://hostname.com:80/folder/file.php?arg=value&b=c#anchor has several components: scheme: http host: hostname.com port: 80 path: folder/file.php query parameters: arg=value&b=c fragment: anchor The query parameters are a set of keys and values. The problem is that often query parameter values conflict with other portions of the query string. For instance if you were doing an address lookup and the url is lookup.php?address=1500 #200 M&M Street, the # of the address conflicts with the anchor fragment, and the & conflicts with a delimiter in the query string. Most languages have a built in function to encode or escape the data so it doesn't conflict. Spaces can be encoded as + or %20, & is encoded as %26, and # as %23. These numbers of course are the characters' hex values from an ascii table. It would be excellent to have a C++ function to automatically encode a url query parameter's value or its uricomponent. PHP provides us with a urlencode function, javascript provides us with 3 escape, encodeURI and encodeURIComponent(). So here is a urlencode() function for c++, it was modeled after javascript's encodeURIComponent(), and uses the php function name, parameter type and return type. #include
#include
using namespace std; string urlencode(const string &c); string char2hex( char dec ); int main(int argc, char *argv[]) { string address = "123 #5 M&M Street"; cout << "address=" << address << endl; cout << "address=" << urlencode(address) <
>4; char dig2 = (dec&0x0F); if ( 0<= dig1 && dig1<= 9) dig1+=48; //0,48inascii if (10<= dig1 && dig1<=15) dig1+=97-10; //a,97inascii if ( 0<= dig2 && dig2<= 9) dig2+=48; if (10<= dig2 && dig2<=15) dig2+=97-10; string r; r.append( &dig1, 1); r.append( &dig2, 1); return r; } Note: It is possible to use sprintf(buffer, "%x", c[i]) to convert a character to hex, but I wanted to avoid using sprintf in this case. http://www.zedwood.com/article/111/cpp-urlencode-function
C++ urlencode function
最新推荐文章于 2024-07-12 16:34:36 发布