美文网首页码农庄园
php或swoole如何使用curl传递接口的json字符串参数

php或swoole如何使用curl传递接口的json字符串参数

作者: 小马过河R | 来源:发表于2021-05-19 16:04 被阅读0次

curl  我们经常说 请求提交用json格式,类似于下图。这自然无可厚非。

但是,如果我们现在就是要传一个json字符串的值呢?类似key=>123, key=>json_str这种形式,且这里要注意json_str可能是['thing4' => ['value' => '幸运大转盘'], 'thing6' => ['value' => '好友成功预约,快来抽奖吧!']]这种含单引号和汉字编码的。如果使用CURL  get 或post是一定要处理url和汉字编码问题的。

问题来自于小马在实现一个 消息推送的接口封装,但是这个消息接口需要接收模板参数,这个模板参数就是个json数组格式的,如下:

$args =[

'templateData' => urlencode(json_encode(['thing4' => ['value' => '幸运大转盘'], 'thing6' => ['value' => '好友成功预约,快来抽奖吧!']],JSON_UNESCAPED_UNICODE)),//如果使用get post    的query参数就需要这样做编码处理

'templateId' => 2,

'templatePage' => ''

  ];

curl 如果直接用get   query传递这些参数,显然会存在url处理编码的问题。所以考虑使用post并放在body中。

用body 这样做的好处就是,发送方不用处理任何编码:

$body = [ 'templateData' => ['thing4' => ['value' => '幸运大转盘'], 'thing6' => ['value' => '好友成功预约,快来抽奖吧!']], 'templateId' => 2, 'templatePage' => '' ]; $options = array();  $options[CURLOPT_CUSTOMREQUEST] = 'POST'; $options[CURLOPT_HTTPHEADER] = array( 'Content-Type:application/json' ); $query_json = json_encode($body,JSON_UNESCAPED_UNICODE);/* $args =[ 'templateData' => urlencode(json_encode(['thing4' => ['value' => '幸运大转盘'], 'thing6' => ['value' => '好友成功预约,快来抽奖吧!']],JSON_UNESCAPED_UNICODE)), 'templateId' => 2, 'templatePage' => '' ]; $args = http_build_query($args);*/ $requestUrl = 'http://miniprogram-user.com/?c=User&a=subscribeMessageSend&'; $backData = curl($requestUrl,$query_json,$options);

接收方也可以直接获得原始的参数:

$bodyArr = json_decode($body,true);

$bodyArr = json_decode($body,true);

就可以得到json字符串参数值,而不需要任何的编码处理。

如下。

我们换种思路,使用post请求将key=>json_str 放在body里请求会更好处理。

那么问题来了,如题,请求接收端该如何接收post请求里的  body参数值呢?

PHP:file_get_contents('php://input');//注意$_REQUEST 是取不到body值的

swoole: $body = $this->request->rawContent();//注意其他函数是取不到body值的

相关文章

网友评论

    本文标题:php或swoole如何使用curl传递接口的json字符串参数

    本文链接:https://www.haomeiwen.com/subject/oeaqrltx.html