Laravel 5 - 使用form_param发出https guzzle请求

时间:2017-08-13 16:22:37

标签: php laravel curl request guzzle

我需要发出POST请求才能领取凭证。在API文档中,我发现了这一点:

POST /vouchers/{voucherId}/claim

{
    "Participant": {
        "FirstName": "John",
        "LastName": "Jones",
        "Telephone": "99999 127 127",
        "EmailAddress": "hahahah@hahaha.net",
        "PostCode": "HP18 9HX",
        "HouseNameNumber": "2",
        "Street": "Bridge Road",
        "Locality": "Ickford",
        "Town": "Lodnon",
        "County": "Bucks"
    },
    "ExperienceDate": "2015-10-01T00:00:00"
}

现在,我使用Laravel guzzle库提出此请求:

 public function testclaim()
    {

$client = new GuzzleHttp\Client;
$headers = ['Content-Type' => 'application/json'];

$res = $client->post('https://apidev.asdasd.com/vouchers/11989898_1-9FDD/claim', [
    'headers'=>$headers,
     'auth' => [
        'PET_RES', 'asdasdasd111111'
    ],
    'form_params' => [

        'FirstName' => 'Peter',
        'LastName' => 'Alexo',
        'Telephone' => '8888888888888'

    ]
            ]);
$res = json_decode($res->getBody()->getContents(), true);

dd($res);

    }

但我得到的是:

  

400错误请求

     

{“消息”:“请求无效。”,“ModelState”:{“claim”:[“An   发生错误。“](截断...)

使用以下数据向API发送请求的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

试试这个

...
'form_params' => [
    'Participant' => [
        'FirstName' => 'Peter',
        'LastName' => 'Alexo',
        'Telephone' => '8888888888888'
    ],
    'ExperienceDate' => '2015-10-01T00:00:00'
]
...

如果您的api只接受json,请尝试将form_params替换为json