[英]CURL with JSON from laravel to API
我正在尝试从系统中实现API调用,并且该API的示例如下所示:
curl -u "<brugernavn>:<password>" -XPOST http://distribution.virk.dk/cvr-permanent/_search -d'
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": 10961211
}
}
}
'
现在我想把它变成PHP代码。 我认为它看起来像这样:
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获取用户名和密码,但是我也不确定如何以正确的方式将用户名和密码与请求一起发送。 是否也有CURLOPT? 我也不确定是否可以像这样用json正确实现我的参数。
谢谢 :)
使用Guzzle库 。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.