首页 文章

URL编码形式为ISO中的ISO-8859-1中的POST

提问于
浏览
0

我正在尝试对只接受ISO-8859-1编码的服务器执行x-www-form-urlencoded HTTP POST .

与Java中的URLEncoder不同,JavaScript中的encodeURIComponent只接受字符串而不进行编码 .

使用iconv转换字符串没有用,因为当调用encodeURIComponent时,编码会丢失(或出现乱码) .

1 回答

  • 0

    我发现了一些支持字符编码的URL编码器,但我没有找到任何尊重RFC 3986中的未保留字符的所有I made one myself .

    var iconv = require('iconv-lite');
    
    var encodeURI = function(str, encoding) {
      if (!encoding || encoding == 'utf8' || encoding == 'utf-8') {
        return encodeURIComponent(str);
      }
    
      var buf = iconv.encode(str, encoding);
      var encoded = [];
    
      for (var pair of buf.entries()) {
        var value = pair[1];
        // Test if value is unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" https://tools.ietf.org/html/rfc3986#section-2.3
        if ((value >= 65 && value <= 90) || // A-Z 
          (value >= 97 && value <= 122) || // a-z
          (value >= 48 && value <= 57) || // 0-9
          value == 45 || value == 46 ||  // "-" / "."
          value == 95 || value == 126   // "_" / "~"      
        ) {
          encoded.push(String.fromCharCode(value));
        } else {
          var hex = value.toString(16).toUpperCase();
          encoded.push("%" + (hex.length === 1 ? '0' + hex : hex));
        }
      }
      return encoded.join("");
    }
    
    module.exports = encodeURI;
    

相关问题