Laravel 中的 cURL 请求

新手上路,请多包涵

我正在努力在 Laravel 中提出这个 cURL 请求

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json"   -X GET http://my.domain.com/test.php

我一直在尝试这个:

 $endpoint = "http://my.domain.com/test.php";

$client = new \GuzzleHttp\Client();

$response = $client->post($endpoint, [
                GuzzleHttp\RequestOptions::JSON => ['key1' => $id, 'key2' => 'Test'],
            ]);

$statusCode = $response->getStatusCode();

但我收到一个错误 Class 'App\Http\Controllers\GuzzleHttp\RequestOptions' not found

有什么建议么?

编辑

我需要从 $response 中获取 API 的响应,然后将其存储在数据库中……我该怎么做? :/

原文由 harunB10 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

试试 Guzzle 的查询选项:

 $endpoint = "http://my.domain.com/test.php";
$client = new \GuzzleHttp\Client();
$id = 5;
$value = "ABC";

$response = $client->request('GET', $endpoint, ['query' => [
    'key1' => $id,
    'key2' => $value,
]]);

// url will be: http://my.domain.com/test.php?key1=5&key2=ABC;

$statusCode = $response->getStatusCode();
$content = $response->getBody();

// or when your server returns json
// $content = json_decode($response->getBody(), true);

我使用这个选项用 guzzle 构建我的 get-requests。结合 json_decode($json_values, true) 您可以将 json 转换为 php-array。

原文由 Brotzka 发布,翻译遵循 CC BY-SA 4.0 许可协议

我相信,从 Laravel 7 开始,Laravel 带有一个 HTTP 客户端,它是 Guzzle HTTP 的包装器。所以现在这样的事情会奏效。

 use Illuminate\Support\Facades\Http;

$response = Http::get('http://my.domain.com/test.php', [
    'key1' => $id,
    'key2' => 'Test',
]);

if ($response->failed()) {
   // return failure
} else {
   // return success
}

这是惊人的,更清洁,更容易测试, 这里是文档

原文由 eballeste 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题