我正在努力用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
中的应用程序接口获得响应,然后将其存储在DB中…我该怎么做?:/
发布于 2018-01-16 19:33:14
试一试Give中的query-option:
$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数组。
发布于 2018-01-16 19:37:56
如果你在使用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框架中的库更好、更简单。但仍然是你的选择,因为你持有你的项目的开发。
发布于 2018-01-16 19:49:10
请将此作为参考。我已经用这段代码成功地发出了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;
}
https://stackoverflow.com/questions/48279382
复制相似问题