简体   繁体   English

C ++中的URL编码和Node.js中的解码

[英]URL encoding in C++ and decoding in nodejs

I am transferring data from a C++ client to a nodejs server. 我正在将数据从C ++客户端传输到nodejs服务器。

I compress the string using zlib deflate first, then I use curl_easy_escape to url encode the compressed string. 我先使用zlib deflate压缩字符串,然后使用curl_easy_escape对所压缩的字符串进行url编码。

std::string s = zlib_compress(temp.str());
std::cout << s <<"\n";
CURL *handle = curl_easy_init();
char* o = curl_easy_escape(handle, s.data(), s.size());
std::cout << o <<"\n";

Then I send it using: 然后我使用以下方式发送:

std::string bin(o);
curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, bin.size());
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, bin.data());
curl_easy_perform(handle);

When I run this, I get the output: 运行此命令时,将得到输出:

x??с??Ҵ4?
x%DA%D3%D1%81%80%E2%92%D2%B44%1D%03%00%1BW%03%E5

Now, I receive the second encoded string on my nodejs server as it is. 现在,我按原样在nodejs服务器上收到第二个编码的字符串。 I now try to decode it. 我现在尝试对其进行解码。

var x = req.params;
for (var key in req.body)
{   
console.log(key);
var x = unescape(key);
var buffer = new Buffer(x);
console.log(x);
zlib.inflate(buffer, function(err, buffer) {

    console.log(err+" here");
});
}

Which outputs: 哪个输出:

x%DA%D3%D1%81%80%E2%92%D2%B44%1D%03%00%1BW%03%E5
xÚÓÑâÒ´4å
Error: incorrect header check here

What is the problem here? 这里有什么问题? How do I debug it? 我该如何调试?

You can debug it by printing the decimal value for each byte in the compressed string in C++ and node.js code. 您可以通过在C ++和node.js代码中为压缩字符串中的每个字节打印十进制值来调试它。 For C++ that code would be: 对于C ++,该代码为:

for(int i=0; i<s.size(); i++) {
    std::cout << static_cast<int>(s[i]);
}

In node.js code you would need to print the decimal value for each byte contained in variable buffer . 在node.js代码中,您需要为变量buffer包含的每个字节打印十进制值。

If the decimal values for each byte are identical in both C++ and node.js parts, then zlib libraries are incompatible or functions do not match: eg zlib_compress in C++ may correspond to something else than zlib.inflate in node.js: maybe there is a function like zlib.decompress() . 如果C ++和node.js部分中每个字节的十进制值都相同,则zlib库不兼容或函数不匹配:例如,C ++中的zlib_compress可能与node.js中的zlib.inflate对应:类似zlib.decompress()的函数。

The root cause can be in that characters are 1-byte in C++ std::string and 2-byte in node.js . 根本原因可能是C ++ std::string中的字符为1个字节,而node.js中的std::string 2个字节。 Specifying the encoding when constructing Buffer in node.js may solve the problem if that is it: 如果是的话,在node.js中构造Buffer时指定编码可以解决问题:

var buffer = new Buffer(x, 'binary');

See https://nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding 请参阅https://nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding

As the data is zlib compressed here, or in a general compressed case, the encoding should be binary . 由于此处是zlib压缩数据,或者在一般压缩情况下,编码应为binary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM