最近在开发智能家居,子模块中调用了图灵机器人(http://tuling123.com/openapi/cloud/home.jsp)
但是发现一直不成功,返回值一直是 40006 百般调试无果 最后发现是中文转码的问题 一般网址都会讲中文进行一次转码,暂且称作 UrlEncode
转码过程很简单,因为中文编码不是一个字节,而是多个字节(ASCLL码为两个, Unicode码为三个),转码过程实际上就是将中文字符按字节输出为 :
%+该字节十六进制表达式
例如 ‘啊’ 字按位输出 则为
则转码之后的 ‘啊’字 为 %b0%a1(Ascll码) ,相同道理 Utf-8 码的 ‘啊’字 转码后为 %e5%95%8a
而字母,数字,以及一些符号如 下划线,~等是不用编码的。
另外注意:空格在网址中不允许出现 被编码为 + 号
则据此可以写出UrlEncode编码的代码
/*
******************************************
Title: UrlEncode转码(Ascll版)
******************************************
Date:2014/12/05
******************************************
author:刘旭
******************************************
*/
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
typedef unsigned char BYTE;
BYTE Int_to_Hex(const BYTE src)
{
return src > 9 ? (src+55) : (src+48);
}
string encode(const string src)
{
string result = "";
int length = src.length();
int pos = 0; //结果字符串的长度标记
for(int i = 0; i < length; i++){
if(isalnum((BYTE)src[i]) || /*判断是否为字母或者数字 必须进行类型转换*/
':' == src[i] ||
'_' == src[i] ||
'.' == src[i] ||
'~' == src[i] ||
'?' == src[i] ||
'&' == src[i] ||
'=' == src[i] ){//因为项目需要,这里我保留了网址里常用的几个字符,其他的字符请查询,时间问题,不多做补充
result += src[i]; //保持不变
}
else if(' ' == src[i]){//如果是空格
result += "+";
}
else {//如果是其他字符
BYTE temp = Int_to_Hex((BYTE) src[i]);
result += "%";
result += Int_to_Hex((BYTE)src[i] >> 4);
result += Int_to_Hex((BYTE)src[i] % 16);
}
}
return result;
}
int main()
{
string src= "你好啊";
string dest = encode(src);
cout<<dest<<endl;
return 0;
}