GuzzleHttp \ Client对Laravel 5.5的错误请求

时间:2018-03-09 10:08:17

标签: php laravel curl guzzle

我正在向API发送POST请求,Curl返回200并返回正确的响应。 使用GuzzleHttp \ Client实现时,我收到400 Bad请求,格式化有什么问题。

这是使用Laravel Returns 400 Bad Request:

的代码
 $client = new Client();

$URI = 'http://api.example.com';
$params['headers'] = ['Content-Type' => 'application/json',
    'apikey' => config('app._api_key'),
    'debug' => true
];
$params['form_params'] = [
    'sender' => 'Test_sender',
    'recipient' => config('app.test_recipient'),
    'message_body' => 'Test  body'
];
return $response = $client->post($URI, $params);

卷曲(返回200):

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'apikey: 212121212’ -d '{ "message_body": "test","sender": "2018","recipient": “4453424141” }' 'http://api.example.com'

3 个答案:

答案 0 :(得分:1)

请尝试以下代码:

$client = new \GuzzleHttp\Client(['headers' => ['Content-Type' => 'application/json',
                                                'apikey'=> config('app._api_key'),
                                                'debug' => true
                                                ]
                                ]);
$URI = 'http://api.example.com';
$body['sender']='Test_sender';
$body['recipient']=config('app.test_recipient');
$body['message_body']='Test  body';
$body=json_encode($body);
$URI_Response = $client->request('POST',$URI,['body'=>$body]);
$URI_Response =json_decode($URI_Response->getBody(), true);
return $URI_Response;

注意:我建议您处理错误,请参阅GuzzleDocumentation

答案 1 :(得分:0)

这是正确的错误处理:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

try {

    $response = $client->get(YOUR_URL, [
        'connect_timeout' => 10
    ]);

    // Here the code for successful request

} catch (RequestException $e) {

    // Catch all 4XX errors 

    // To catch exactly error 400 use 
    if ($e->getResponse()->getStatusCode() == '400') {
            echo "Got response 400";
    }

    // You can check for whatever error status code you need 

} catch (\Exception $e) {

    // There was another exception.

}

实施:http://guzzle.readthedocs.org/en/latest/quickstart.html

答案 2 :(得分:0)

你可以处理这样的错误

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Exception;


try{
    $client = new Client();

    $response = $client->request('POST', $url,[
         'headers' => $header,
         'form_params' => $form-params
    ]);
    $body = $response->getBody();
    $status = 'true';
    $message = 'Data found!';
    $data = json_decode($body);
}catch(ClientException $ce){
    $status = 'false';
    $message = $ce->getMessage();
    $data = [];
}catch(RequestException $re){
   $status = 'false';
   $message = $re->getMessage();
   $data = [];
}catch(Exception $e){
   $this->status = 'false';
   $this->message = $e->getMessage();
   $data = [];
}

return ['status'=>$status,'message'=>$message,'data'=>$data];