【问题标题】:CURL with JSON from laravel to API从 laravel 到 API 的 JSON 卷曲
【发布时间】:2019-09-18 04:11:53
【问题描述】:

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

谢谢你:)

【问题讨论】:

标签: php laravel api curl


【解决方案1】:

使用Guzzle library。 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);
}

【讨论】:

猜你喜欢
  • 2015-03-25
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2015-09-09
  • 2018-07-08
  • 1970-01-01
  • 2014-02-15
  • 2016-08-12
相关资源
最近更新 更多