0

我正在尝试从我的系统实现 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 正确方式实现。

谢谢你 :)

4

1 回答 1

1

使用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);
}
于 2019-04-29T17:01:06.070 回答