简体   繁体   English

curl 的 json_decode 反序列化错误

[英]json_decode deserialization error with curl

I've created a Rest API that is working well, but I noticed a strange thing.我创建了一个运行良好的 Rest API,但我注意到了一件奇怪的事情。 For deserializing the content sent by the client I use this code:为了反序列化客户端发送的内容,我使用以下代码:

var_dump(json_decode(file_get_contents("php://input"), true));

If I send a request with POSTMAN (Chrome Extension), all is working well, see:如果我使用POSTMAN (Chrome 扩展程序)发送请求,则一切正常,请参阅:

在此处输入图片说明

but if I use curl with MINGW64 , I'll get NULL :但是如果我将curlMINGW64一起MINGW64 ,我会得到NULL

在此处输入图片说明

Now in both cases, I checked the encoding type which was with this code:现在,在这两种情况下,我都检查了此代码的编码类型:

$content = file_get_contents("php://input");
$encode =  mb_detect_encoding($content, "auto");
$json = mb_convert_encoding($content, $encode);
var_dump($json);

and this returns UTF-8这将返回UTF-8

I don't understand why, with curl MINGW64 , the console is not working, yet with the extension, or is working.我不明白为什么使用 curl MINGW64 ,控制台不工作,但有扩展,或者正在工作。 What's happeni.g?怎么了?

UPDATE更新

I've executed this function: json_last_error() , and it returned 5 .我已经执行了这个函数: json_last_error() ,它返回了5 On this site , I saw that the number corresponds to an error:在这个网站上,我看到这个数字对应一个错误:

5 = JSON_ERROR_UTF8

But I have no idea what is wrong.但我不知道出了什么问题。

Since you are submitting JSON data in the body, you need to tell the server the content-type, otherwise cURL is sending it as application/x-www-form-urlencoded . 由于您要在正文中提交JSON数据,因此需要告诉服务器内容类型,否则cURL会将其作为application/x-www-form-urlencoded

Additionally, any UTF-8 characters need to be encoded in \\uXXXX format to have a valid JSON string. 此外,任何UTF-8字符都需要以\\uXXXX格式编码才能具有有效的JSON字符串。

Try: 尝试:

curl -i -H "token: company" \
-H "Content-type: application/json" \
-d '{"Code": "R89d", "Descri": "Questo \u00E8 un test"}' \
-X PUT http://localhost/api/customer/add

Edit: 编辑:

Not sure what you're starting out with, but you can use the following two commands to supply cURL with a proper JSON string. 不确定您从什么开始,但是可以使用以下两个命令为cURL提供正确的JSON字符串。

var=$(php -r 'echo json_encode(["Code" => "R89d", "Descri" => "Questo è un test"]);')
curl -v -H "Content-type: application/json" -d "$var" http://sandbox/test.php

Converting encoding to utf-8 worked for me.将编码转换为 utf-8 对我有用。 $retorno_transaction = mb_convert_encoding($retorno_transaction, 'UTF-8');

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

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