laravel 使用 Guzzle 用 JSON 发送 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46387679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:42:38  来源:igfitidea点击:

Using Guzzle to send POST request with JSON

phplaravelguzzle

提问by Kira

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

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

return $request;

And I get back 502 Bad Gatewayand Resource interpreted as Document but transferred with MIME type application/json

我回来了502 Bad Gateway,资源被解释为文档,但用 MIME 类型应用程序/json 传输

I need to make a POST request with some json. How can I do that with Guzzle in Laravel?

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

回答by Morteza Rajabi

Give it a try

试一试

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

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

回答by rAm

Take a look..

看一看..

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

回答by pankaj kumar

you can also try this solution. that is working on my end. I am using Laravel 5.7.

你也可以试试这个解决方案。这对我有用。我正在使用Laravel 5.7

This is an easy solution of Make a POST Requestfrom PHPWith Guzzle

这是使用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();
  }

For Use this method

对于使用此方法

    $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']]);
    }