【问题标题】:Using Guzzle to send POST request with JSON使用 Guzzle 发送带有 JSON 的 POST 请求
【发布时间】:2017-09-24 07:31:46
【问题描述】:
$client = new Client();
$url = 'api-url';

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

return $request;

然后我返回 502 Bad Gateway 并将资源解释为 Document 但使用 MIME 类型 application/json 传输

我需要使用一些 json 发出 POST 请求。我如何在 Laravel 中使用 Guzzle 做到这一点?

【问题讨论】:

    标签: php laravel guzzle


    【解决方案1】:

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

    这是使用 GuzzlePHP 发出 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']]);
        }
    

    【讨论】:

    • 问题询问如何使用 JSON 发送请求。这个例子不起作用。
    • 你能分享你得到的错误代码吗?
    • 你能分享你得到的错误吗......因为在我的服务器上它正在工作......
    • 不,这两种方法都在我的项目中工作。我在我的项目中多次遇到同样的问题。我为此使用了 CURL .. 但感谢 Pankaj ji...
    • 请帮帮我,我需要一些技术支持请致电我 9031261290
    【解决方案2】:

    试试看

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

    【讨论】:

    • @KiraArik 您使用的是哪个版本的 Guzzle?
    • 它应该是 dd() 中的 $request 而不是 $result。并且缺少一个方括号。 $request = $client->post('api.example.com', [ 'json' => [ 'key' => 'value' ] ]); dd($request->getBody()->getContents());
    【解决方案3】:

    看看..

    $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();
    

    【讨论】:

      猜你喜欢
      • 2020-07-14
      • 2022-02-21
      • 2014-04-10
      • 1970-01-01
      • 2018-03-21
      • 2014-06-06
      • 2019-05-27
      相关资源
      最近更新 更多