laravel中的cURL请求

har*_*B10 9 php curl laravel guzzle

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

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

我一直在尝试这个:

$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();
Run Code Online (Sandbox Code Playgroud)

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

有什么建议?

编辑

我需要从API中获取响应$response然后将其存储在DB中...我该怎么做?:/

Bro*_*zka 17

从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' => 'Test'
]]);

// 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);
Run Code Online (Sandbox Code Playgroud)

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


eba*_*ste 7

我相信,从 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
}
Run Code Online (Sandbox Code Playgroud)

它太棒了,更干净,更容易测试,这是文档

  • 对于 Laravel 8+,您必须先运行“composer require guzzlehttp/guzzle”,然后才能在代码中使用 Http 包装器。(https://laravel.com/docs/9.x/http-client#introduction) (2认同)

Ken*_*day 6

如果在使用guzzlehttp时遇到问题,仍可以在PHP中使用本机cURL:

原生php方式

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "SOME_URL_HERE".$method_request);
// SSL important
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$output = curl_exec($ch);
curl_close($ch);


$this - > response['response'] = json_decode($output);
Run Code Online (Sandbox Code Playgroud)

有时,此解决方案比使用Laravel框架中附带的库更好,更简单。但自从您掌握了项目的开发以来,仍然是您的选择。


小智 5

以此作为参考。我已使用此代码成功发出 curl GET 请求

public function sendSms($mobile)
{
  $message ='Your message';
  $url = 'www.your-domain.com/api.php?to='.$mobile.'&text='.$message;

     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

     $response = curl_exec ($ch);
     $err = curl_error($ch);  //if you need
     curl_close ($ch);
     return $response;
}
Run Code Online (Sandbox Code Playgroud)