我正努力在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的响应,然后将其存储在DB中...我该怎么做? :/
从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);
我用这个选项用guzzle来构建我的get-requests。结合json_decode($ json_values,true),你可以将json转换为php-array。
如果你在使用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);
有时这个解决方案比使用Laravel框架中附带的库更好更简单。但是,自从您掌握项目开发以来,仍然是您的选择。
使用此作为参考。我已成功使用此代码进行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;
}