当URL的参数中有中文格式的时候要进行编码解码

来源:互联网 发布:北京行知园地址 编辑:程序博客网 时间:2024/05/16 12:28

例如:

原版

http://192.168.1.207:8080/Rice_ssm/equipment/swipingCard.action?RTUID=00000001&count=1&riceThickness=1&totalPrice=5&riceName=湖南大米&read_IC_num=000001&price=30

解码后

http://192.168.1.207:8080/Rice_ssm/equipment/swipingCard.action?RTUID=00000001&count=1&riceThickness=1&totalPrice=5&riceName=%E6%B9%96%E5%8D%97%E5%A4%A7%E7%B1%B3&read_IC_num=000001&price=30


#include "App_includes.h"

#define BURSIZE 1024


int hex2dec(char c)
{
    if ('0' <= c && c <= '9') {
        return c - '0';
    } else if ('a' <= c && c <= 'f') {
        return c - 'a' + 10;
    } else if ('A' <= c && c <= 'F') {
        return c - 'A' + 10;
    } else {
        return -1;
    }
}


char dec2hex(short int c)
{
    if (0 <= c && c <= 9) {
        return c + '0';
    } else if (10 <= c && c <= 15) {
        return c + 'A' - 10;
    } else {
        return -1;
    }
}




/*
 * 编码一个url
 */
void urlencode(char *url,char *encodeurl)
{
    int i = 0;
    int len = strlen(url);
    int res_len = 0;
    char res[BURSIZE];
    for (i = 0; i < len; ++i) {
        char c = url[i];
        if (('0' <= c && c <= '9') ||
                ('a' <= c && c <= 'z') ||
                ('A' <= c && c <= 'Z') || c == '/' || c == '.'|| c == ':' || c == '_' || c == '=' || c == '&'|| c == '?'|| c == '\0') {
            res[res_len++] = c;
        } else {
            int j = (short int)c;
            if (j < 0)
                j += 256;
            int i1, i0;
            i1 = j / 16;
            i0 = j - i1 * 16;
            res[res_len++] = '%';
            res[res_len++] = dec2hex(i1);
            res[res_len++] = dec2hex(i0);
        }
    }
    res[res_len] = '\0';


   strcpy(encodeurl, res);


}


/*
 * 解码url
 */
void urldecode(char *url)
{
    int i = 0;
    int len = strlen(url);
    int res_len = 0;
    char res[BURSIZE];
    for (i = 0; i < len; ++i) {
        char c = url[i];
        if (c != '%') {
            res[res_len++] = c;
        } else {
            char c1 = url[++i];
            char c0 = url[++i];
            int num = 0;
            num = hex2dec(c1) * 16 + hex2dec(c0);
            res[res_len++] = num;
        }
    }
    res[res_len] = '\0';
    strcpy(url, res);
}

0 0
原创粉丝点击