Suc*_*Man 1 php laravel guzzle guzzle6 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
}
}
Run Code Online (Sandbox Code Playgroud)
执行时,结果为空
我怎样才能得到回应?
我尝试邮递员,成功得到回应
但我尝试使用 guzzle,但失败了
更新 :
我检查了邮递员,结果有效
我尝试点击邮递员上的按钮代码
然后我选择 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;
}
Run Code Online (Sandbox Code Playgroud)
如果它使用curl php,代码就是这样
如果使用 guzzle,我如何获得响应?
我看到至少一个语法错误。该request()方法的第三个参数应如下所示:
$requestContent = [
'headers' = [],
'json' = []
];
Run Code Online (Sandbox Code Playgroud)
在你的情况下,它可能是:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
还有其他参数代替json您的数据,例如form_params. 我建议您查看Guzzle 文档。