首页 > 代码库 > URL Encode
URL Encode
用VC实现post数据常常会遇到URL编码问题
在此封装一个工具类进行UTF8编码的转换
源码来自php source code
只是简单的封装给C++调用
[cpp] view plaincopy
- //URL 编解码类
- //来自PHP源码
- class CRtUrlConv
- {
- public:
- static char *urlencode(const char *in_str )
- {
- char *out_str;
- int in_str_len, out_str_len;
- in_str_len=strlen(in_str);
- out_str_len=0;
- out_str = php_url_encode( in_str , in_str_len, &out_str_len);
- return (char *) out_str;
- }
- static int urldecode(char *s)
- {
- return php_url_decode(s);
- }
- private:
- static char *php_url_encode(const char *s , int len , int *new_length)
- {
- register unsigned char c;
- unsigned char *to, *start;
- unsigned char const *from, *end;
- from = (unsigned char *)s;
- end = (unsigned char *)s + len;
- start = to = new unsigned char[3*len+1];
- while (from < end) {
- c = *from++;
- if (c == ‘ ‘) {
- *to++ = ‘+‘;
- #ifndef CHARSET_EBCDIC
- } else if ((c < ‘0‘ && c != ‘-‘ && c != ‘.‘) ||
- (c < ‘A‘ && c > ‘9‘) ||
- (c > ‘Z‘ && c < ‘a‘ && c != ‘_‘) ||
- (c > ‘z‘)) {
- to[0] = ‘%‘;
- to[1] = HEXCHARS[c >> 4];
- to[2] = HEXCHARS[c & 15];
- to += 3;
- #else /*CHARSET_EBCDIC*/
- } else if (!isalnum(c) && strchr("_-.", c) == NULL) {
- /* Allow only alphanumeric chars and ‘_‘, ‘-‘, ‘.‘; escape the rest */
- to[0] = ‘%‘;
- to[1] = HEXCHARS[os_toascii[c] >> 4];
- to[2] = HEXCHARS[os_toascii[c] & 15];
- to += 3;
- #endif /*CHARSET_EBCDIC*/
- } else {
- *to++ = c;
- }
- }
- *to = 0;
- if (new_length) {
- *new_length = to - start;
- }
- return (char *) start;
- }
- static int php_url_decode(char *str)
- {
- int len;
- char *dest = str;
- char *data = str;
- len=strlen(str);
- while (len--) {
- if (*data == ‘+‘) {
- *dest = ‘ ‘;
- }
- else if (*data == ‘%‘ && len >= 2 && isxdigit((int) *(data + 1))
- && isxdigit((int) *(data + 2))) {
- #ifndef CHARSET_EBCDIC
- *dest = (char) php_htoi(data + 1);
- #else
- *dest = os_toebcdic[(char) php_htoi(data + 1)];
- #endif
- data += 2;
- len -= 2;
- } else {
- *dest = *data;
- }
- data++;
- dest++;
- }
- *dest = ‘/0‘;
- return dest - str;
- }
- static int php_htoi(char *s)
- {
- int value;
- int c;
- c = ((unsigned char *)s)[0];
- if (isupper(c))
- c = tolower(c);
- value = (c >= ‘0‘ && c <= ‘9‘ ? c - ‘0‘ : c - ‘a‘ + 10) * 16;
- c = ((unsigned char *)s)[1];
- if (isupper(c))
- c = tolower(c);
- value += c >= ‘0‘ && c <= ‘9‘ ? c - ‘0‘ : c - ‘a‘ + 10;
- return (value);
- }
- static const char hexchars[];
- static const char HEXCHARS[];
- };
- const char CRtUrlConv::hexchars[] = "0123456789abcdef";
- const char CRtUrlConv::HEXCHARS[] = "0123456789ABCDEF";
- }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。