【问题标题】:Convert cURL request to Guzzle in Laravel在 Laravel 中将 cURL 请求转换为 Guzzle
【发布时间】:2017-04-04 10:24:33
【问题描述】:

我在 Codeigniter 中有如下 curl 请求:

$order = [
  'index' => 'Value',
  'index2' => 'Value2'
];

$this->curl->create($this->base_url.'order/');
$this->curl->http_login($creds['username'], $creds['password']);
$this->curl->ssl(TRUE, 2, 'certificates/certificate.pem');
$this->curl->option(CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
$this->curl->option(CURLOPT_FAILONERROR, FALSE);

$this->curl->post(json_encode($order));
$data   = $this->curl->execute();

现在我需要在使用 Guzzle 的 Laravel 中发出相同的请求。如何将其转换为 Guzzle 请求?

【问题讨论】:

    标签: php laravel curl guzzle


    【解决方案1】:

    非常非常简单:

    $client = new GuzzleHttp\Client(['base_uri' => $this->base_url]);
    
    $response = $client->request('POST', 'order/', [
      'form_params' => $order,
      'headers' => [
        'Content-Type' => 'application/json',
        'Accept' => 'application/json'
      ],
      'auth' => [$creds['username'], $creds['password']],
      'http_errors' => false,
      'verify' => 'certificates/certificate.pem'
    ]);
    
    echo $response->getBody();
    

    请注意,这与 Laravel 无关,它只是 Guzzle。 Laravel 不会以任何方式影响 Guzzle API。

    【讨论】:

    • 那么 SSL 和证书呢?
    • @HappyCoder Guzzle 默认支持 SSL 请求,我假设您的 base_url() 返回一个以 https:// 开头的字符串
    • @HappyCoder 但如果您使用的是自签名证书,您可以添加 'verify' => 'certificates/certificate.pem' 或 'verify' => false 禁用 SSL 证书检查
    • 这里还有一个与 Auth 相关的问题。 API 正在使用基本的 http 身份验证,但它返回错误 Authorization Required。用户名和密码正确,因为我在 Postman 客户端中使用时得到响应。
    • @HappyCoder 用于基本身份验证,只需从数组中删除最后一项('digest')
    猜你喜欢
    • 2019-12-17
    • 2017-01-13
    • 2015-11-02
    • 2015-02-13
    • 1970-01-01
    • 2021-11-30
    • 2014-09-17
    • 2013-10-30
    • 2016-03-21
    相关资源
    最近更新 更多