使用request请求post,如何以GB2312方式请求?
发布于 9 年前 作者 raofeng 5388 次浏览 最后一次编辑是 8 年前 来自 问答

现在有一个蛋疼的短信接口,接收数据只支持GB2312,默认使用request请求出去的数据,接口收到的都是乱码。 直接新建一个ANSI文件格式的html,写个表单提交就没有问题,文件格式如果是UTF-8也同样是乱码。 请问如何解决?在线等,感谢。

5 回复

这是urlEncode的原因,node本身不支持GBK, 需要第三方模块进行合适的编码才能输出流。看我博客node 提交中文参数

/**
*服务器接收的是GBK参数,响应也是GBK编码页面
*/
var form = {  
    msg:'蛤',
    psw:'2333'
}

var postData = querystring.stringify(form, null, null,  
  { encodeURIComponent: function (str){
    var chinese = new RegExp(/[^\x00-\xff]/g);
      var gbkBuffer = null;
      var i = 0;
      var tempStr = '';
      if (chinese.test(str)){//
        gbkBuffer = iconv.encode(str,'gbk');
      for (i;i<gbkBuffer.length;i++){
        tempStr += '%' + gbkBuffer[i].toString(16);
      };
      tempStr = tempStr.toUpperCase();
        return tempStr;
    }else{
        return querystring.escape(str);
    }
  }
});

var options = {  
  hostname: 'localhost',
  port: 8080,
  path: '/test/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }//Cookie也是放在请求头里面
};

var req = http.request(options, function(res) {  
  console.log('STATUS: ' + res.statusCode);
  //响应的Cookie在res.header['set-cookie']
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  // res.setEncoding('binary');//接收参数的时候先不要解码,或者解码为二进制
  res.on('data', function (chunk) {
    console.log('BODY: ' + iconv.decode(chunk,'gbk'));//gbk解码
  });
});

req.on('error', function(e) {  
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write(postData);  
req.end();  

Content-Length:postData.length 这种写法是不对的。 Content-Length:Buffer.byteLength(postData, ‘gb2312’) 应该是这样

你试试

@xiaxiaokang content-length只是服务器判断请求发送完没有,不会影响到能否成功解码。 主要是encodeURIComponent

同意iconv😄

回到顶部