C++ urlencode function

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值