PHP用HTTP协议传输Protobuf数据时,为什么会出现“I/O error while reading input message”错误?

php用http协议传输protobuf数据时,为什么会出现“i/o error while reading input message”错误?

PHP使用HTTP协议传输Protobuf数据时解决“I/O error while reading input message”错误

本文分析了PHP通过HTTP请求传输Protobuf序列化数据时,出现“I/O error while reading input message”错误的原因,并提供了解决方案。该问题通常发生在与第三方API对接,使用Protobuf作为序列化协议时。

开发者按照文档要求,使用HTTP协议、Protobuf 3序列化协议以及Content-Type: application/x-protobuf HTTP头。 Protobuf消息的序列化和反序列化本身没有问题,但HTTP请求发送失败。服务器返回的错误信息提示输入消息读取错误,Protobuf解析异常,表明输入数据可能被截断或消息长度报告错误。

问题代码片段:

立即学习PHP免费学习笔记(深入)”;

$options = [
    'headers' => [
        'content-type' => 'application/x-protobuf',
    ],
    'json' => $pack // 错误:将Protobuf字节流作为JSON参数传递
];
$response = $this->request(self::$api, [], 'post', $options);
登录后复制

错误在于将Protobuf序列化后的字节流$pack作为json参数传递。HTTP客户端库会尝试将$pack进行JSON编码,导致Protobuf字节流被错误处理,服务器无法正确解析。 application/x-protobuf 内容类型明确指定传输的是Protobuf二进制数据,而非JSON数据。

解决方案:

直接将$pack作为请求体发送,而非JSON数据。 以下使用cURL库的示例:

$ch = curl_init(self::$api);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pack); // 正确:直接传递Protobuf字节流
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-protobuf']);
// ...其他cURL设置...
登录后复制

通过直接传递Protobuf字节流作为请求体并设置正确的Content-Type头,服务器能够正确接收和解析数据,从而避免“I/O error while reading input message”错误。 请根据实际使用的HTTP客户端库调整代码。 不同库的请求体和HTTP头设置方法可能有所不同。

以上就是PHP用HTTP协议传输Protobuf数据时,为什么会出现“I/O error while reading input message”错误?的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1235581.html

发表回复

Your email address will not be published. Required fields are marked *