首页 > 解决方案 > 为什么我使用 Guzzle 对 API 的发布请求不起作用?

问题描述

我想向 API 发出发布请求以创建新客户端,但出现错误:

Client error: `POST https://testname.app.invoicexpress.com/document-type.json?api_key=...` 
resulted in a `404 Not Found` response: <!doctype html> 
 <!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en">
 <![endif]--> <!--[if IE 7]> <html class="n (truncated...)

在文档“ https://developers.invoiceexpress.com/docs/versions/2.0.0/resources/invoices ”中说要创建一个新客户端以及发票,curl 命令如下:

  curl --request POST \
      --url 'https://account_name.app.invoicexpress.com/:document-type.json?api_key=YOUR%20API%20KEY%20HERE' \
      --header 'accept: application/json' \
      --header 'content-type: application/json' \
      --data '{"invoice":{"date":"03/12/2017","due_date":"03/12/2017","client":{"name":"Client Name","code":"A1"},"items":[{"name":"Item Name","description":"Item Description","unit_price":"100","quantity":"5"}]}}'

但是使用下面的代码而不是 curl 命令,它会显示该错误。

public function generateInvoice()
{

    $client = new \GuzzleHttp\Client();

    $array = [
        'invoice' => [
            'date' => '03/12/2017',
            'due_date' => '03/12/2017',
            'client' => [
                'name' => 'Client Name',
                'code' => 'A1'
            ],
            'items' => [
                [
                    'name' => 'Item Name',
                    'description' => 'Item Description',
                    'unit_price' => '100',
                    'quantity' => '5'
                ]
            ]
        ]
    ];

    $response = $client->request('POST', 'https://testname.app.invoicexpress.com/invoices.json', [
        'query' => ['api_key' => '...'], 'form_params' => [$array],
    ]);
    dd($response->getStatusCode());

}

Wihout [] 并且只有 $array 在 'form_params' 显示:

 Client error: 
   `POST https://testname.app.invoicexpress.com/invoices.json?api_key=...` resulted 
   in a `422 Unprocessable Entity` 
   response: {"errors":[{"error":"Items element should be of type    array"}]}

标签: phplaravelguzzle

解决方案


尝试用'json'重命名你的参数'form_param'

喜欢:'form_params' => [$array] to'json' => [$array]


推荐阅读