使用Guzzle使用JSON发送POST请求

时间:2017-09-24 07:31:47

标签: php laravel guzzle

$client = new Client();
$url = 'api-url';

$request = $client->post($url, [
    'headers' => ['Content-Type' => 'application/json'],
    'json' => ['token' => 'foo']
]);

return $request;

然后我回来502 Bad Gateway并将资源解释为文档,但使用MIME类型application / json进行传输

我需要用一些json发出POST请求。我怎么能在Laravel的Guzzle中做到这一点?

3 个答案:

答案 0 :(得分:5)

试一试

$response = $client->post('http://api.example.com', [
    'json' => [
       'key' => 'value'
     ]
]);

dd($response->getBody()->getContents());

答案 1 :(得分:0)

看看..

$client = new Client();

$url = 'api-url';

$headers = array('Content-Type: application/json');

$data = array('json' => array('token' => 'foo'));

$request = new Request("POST", $url, $headers, json_encode($data));

$response = $client->send($request, ['timeout' => 10]);

$data = $response->getBody()->getContents();

答案 2 :(得分:0)

您也可以尝试此解决方案。这对我有帮助。我正在使用 Laravel 5.7

这是使用 Guzzle

PHP 发出 POST请求的简单解决方案
   function callThirdPartyPostAPI( $url,$postField  )
   {
     $client = new Client();
     $response = $client->post($url , [
        //'debug' => TRUE,
        'form_params' => $postField,
        'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        ]
     ]);
    return $body = $response->getBody();
  }
  

使用此方法

    $query['schoolCode'] =$req->schoolCode;
    $query['token']=rand(19999,99999);
    $query['cid'] =$req->cid;
    $query['examId'] =$req->examId;
    $query['userId'] =$req->userId;

    $tURL = "https://www.XXXXXXXXXX/tabulation/update";

    $response = callThirdPartyPostAPI($tURL,$query);

    if(  json_decode($response,true)['status'] )
    {
        return success(["data"=>json_decode($response,true)['data']]);
    }
相关问题