我正在努力在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中...我该怎么做? :/
答案 0 :(得分:11)
尝试从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数组。
答案 1 :(得分: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);
有时这个解决方案比使用Laravel框架中附带的库更好更简单。但是,自从你掌握项目的开发以来,仍然是你的选择。
答案 2 :(得分:2)
使用此作为参考。我已成功使用此代码生成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;
}
答案 3 :(得分:0)
使用Laravel,如果您使用的是WP并且感到冒险并且不想使用食人鱼或laravel curl包,则可以在route文件中编写类似的内容。
Route::get('/curl',function() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.net/wp-login.php');
// save cookies to 'public/cookie.txt' you can change this later.
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_POSTFIELDS, ['log'=>'<name>','pwd'=>'<pass>']);
curl_exec($ch);
// supply cookie with request
curl_setopt($ch, CURLOPT_COOKIE, 'cookie.txt');
// the url you would like to visit
curl_setopt($ch, CURLOPT_URL, 'https://example.net/profile/');
$content = curl_exec($ch);
curl_close($ch);
// webpage will be displayed in your browser
return;
});
答案 4 :(得分:0)
您忘记在命名空间前添加\。
您应该写:
$response = $client->post($endpoint, [
\GuzzleHttp\RequestOptions::JSON => ['key1' => $id, 'key2' => 'Test'],
]);
代替:
$response = $client->post($endpoint, [
GuzzleHttp\RequestOptions::JSON => ['key1' => $id, 'key2' => 'Test'],
]);