post提交GBK格式
这种情况改怎么提交参数呢,求大神指点
4 回复
提交和编码是2回事 按正常post提交就行了
@imhered 正常提交,接口确实返回
string先转成GBK编码的buffer(可以用 https://github.com/ashtuchkin/iconv-lite),然后每个byte转成 %XX。 注意不能用 encodeURIComponent ,这个总是按照 utf8 转的(汉字3个字节)
以前写一个短信接口的时候碰到过,这是我当时写的,
'use static';
const http = require('http');
const moment = require('moment');
const iconv = require('iconv-lite');
const querystring = require('querystring');
const { logger } = require('./log');
const sms = (phone, txt) => {
const postData = querystring.stringify({
SpCode: '',
LoginName: '',
Password: '',
MessageContent: txt,
UserNumber: phone,
SerialNumber: moment().format('x') + moment().format('SSS'),
ScheduleTime: moment().format('YYYYMMDDHHmmss'),
}, null, null, {
encodeURIComponent: str => {
let gbkBuffer = null;
let tempStr = '';
if (/[^\x00-\xff]/g.test(str)) {
gbkBuffer = iconv.encode(str, 'gbk');
for (let i = 0; i < gbkBuffer.length; i++) {
tempStr += '%' + gbkBuffer[i].toString(16);
};
tempStr = tempStr.toUpperCase();
return tempStr;
} else {
return querystring.escape(str);
}
}
});
const req = http.request({
hostname: '',
port: 8888,
path: '',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
},
}, res => {
res.on('data', chunk => {
logger.info(phone + ': ' + iconv.decode(chunk, 'gbk'));
});
});
req.on('error', e => {
logger.info(phone + ': ' + e.message);
});
req.write(postData);
req.end();
}
module.exports = sms;