如何从 Laravel 5.3 中的 guzzle 6 获得响应?

How can I get response from guzzle 6 in Laravel 5.3?

我从这里读到:http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client

我这样试:

...
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\RequestException;
...
public function testApi()
{
    try {
        $client = new GuzzleHttpClient();
        $apiRequest = $client->request('POST', 'https://myshop/api/auth/login', [
            // 'query' => ['plain' => 'Ab1L853Z24N'],
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'auth' => ['test@gmail.com', '1234'],       //If authentication required
            // 'debug' => true                                  //If needed to debug   
        ]);
        $content = json_decode($apiRequest->getBody()->getContents());
        dd($content);
    } catch (RequestException $re) {
          //For handling exception
    }
}

执行时,结果为空

我怎样才能得到回复?

我在邮递员中尝试,它成功得到响应

但是我尝试使用guzzle,失败了

更新:

我查了一下邮递员,结果有效

我试试邮递员上的点击按钮代码

然后我 select php curl 然后我复制它,结果是这样的:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://myshop/api/auth/login",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\ntest@gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n1234\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    "postman-token: 1122334455-abcd-edde-aabe-adaddddddddd"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

如果使用curl php,代码就是这样

如果使用guzzle,如何获取响应?

我发现至少一个语法错误。 request() 方法的第三个参数应该是这样的:

$requestContent = [
    'headers' = [],
    'json' = []
];

你的情况可能是:

public function testApi()
{
    $requestContent = [
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'email' => 'test@gmail.com',
            'password' => '1234',
            // 'debug' => true
        ]
    ];

    try {
        $client = new GuzzleHttpClient();

        $apiRequest = $client->request('POST', 'https://myshop/api/auth/login', $requestContent);

        $response = json_decode($apiRequest->getBody());

        dd($response);
    } catch (RequestException $re) {
          // For handling exception.
    }
}

您的数据还有其他参数而不是 json,例如 form_params。我建议你看看 the Guzzle documentation.