Php 使用JSON从laravel到API的CURL
我正在尝试从我的系统实现一个API调用,API有一个如下示例:Php 使用JSON从laravel到API的CURL,php,laravel,api,curl,Php,Laravel,Api,Curl,我正在尝试从我的系统实现一个API调用,API有一个如下示例: curl -u "<brugernavn>:<password>" -XPOST http://distribution.virk.dk/cvr-permanent/_search -d' { "from" : 0, "size" : 1, "query": { "term": { "cvrNummer": 10961211 } } } ' public
curl -u "<brugernavn>:<password>" -XPOST http://distribution.virk.dk/cvr-permanent/_search -d'
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": 10961211
}
}
}
'
public function requestApiV2($vat){
// Start cURL
$ch = curl_init();
// Determine protocol
$protocol = 'http';
$parameters = json(
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": $vat
}
}
}
);
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $protocol . '://distribution.virk.dk/cvr-permanent/_search' . http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Parse result
$result = curl_exec($ch);
// Close connection when done
curl_close($ch);
// Parse from json to array
$data = json_decode($result, true);
}
我还不能测试这个,因为我仍然需要从API获取用户名和密码,但我也不确定如何以正确的方式发送用户名和密码以及请求。这个也有选择吗?
我还不确定我的参数是否以正确的方式使用json实现
谢谢:)使用。Laravel包含Guzzle库,因此您无需安装它
有了Guzzle,下面就可以了
use GuzzleHttp\Client;
public function requestApiV2($vat){
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://distribution.virk.dk/,
]);
$response = $client->post('cvr-permanent/_search', [
'auth' => ['username', 'password'],
'json' => [
'from' => 0,
'size' => 1,
'query' => [
'term' => [
'cvrNumber' => $vat
]
]
]
]);
$body = $response->getBody();
dd($body);
}
可能是复制品好的,看起来不错。它如何知道将$vat放在哪里?另外,我如何处理退货?我希望从apicheck for Guzzle响应对象返回一堆json数据