首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >以Laravel表示的cURL请求

以Laravel表示的cURL请求
EN

Stack Overflow用户
提问于 2018-01-16 18:44:18
回答 6查看 126.4K关注 0票数 29

我正在努力用Laravel发出这个cURL请求

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

我一直在尝试这样做:

代码语言:javascript
复制
$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中…我该怎么做?:/

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2018-01-16 19:33:14

试一试Give中的query-option:

代码语言:javascript
复制
$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数组。

票数 47
EN

Stack Overflow用户

发布于 2018-01-16 19:37:56

如果你在使用guzzlehttp时遇到问题,你仍然可以在PHP中使用原生cURL:

原生Php

代码语言:javascript
复制
$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框架中的库更好、更简单。但仍然是你的选择,因为你持有你的项目的开发。

票数 15
EN

Stack Overflow用户

发布于 2018-01-16 19:49:10

请将此作为参考。我已经用这段代码成功地发出了curl GET请求

代码语言:javascript
复制
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;
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48279382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档