如何在 Laravel 中发送 PUT 请求

How do i send a PUT request in Laravel

我正在尝试通过向 ServiceDesk plus api 发送 http put 请求来更新数据。使用系统附带的控制台时,它运行良好,但是当我尝试从 Laravel 向同一个 api 发送请求时,它不起作用。

来自下方控制台的请求

我正在尝试使用下面的代码向同一个 url 发送请求。

 private function openTicket($notification)
 {
    $data = json_encode(['input_data' => ['request' => ['subject' => $notification->subject,
            'description' => $notification->description,
            'status' => ['name' => 'Open']]]]);


    $request_id = $notification->request_id;
    $response = Http::withHeaders([
            'technician_key' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX',
            'Accept' => 'application/json'
    ])->put('http://localhost:8082/api/v3/requests/' . $request_id, $data);

     dd($response);
    }

我收到错误 400 错误请求

你不应该做json_encode,laravel Http模块会自动为你做。我认为您的数据现在是 json_encoded 的两倍。

$data = [
  'input_data' => [
    'request' => [
      'subject' => $notification->subject,
      'description' => $notification->description,
      'status' => ['name' => 'Open']
    ]
  ]
]);


    $request_id = $notification->request_id;
    $response = Http::withHeaders([
            'technician_key' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX',
            'Accept' => 'application/json'
    ])->put('http://localhost:8082/api/v3/requests/' . $request_id, $data);

     dd($response);

我刚注意到。根据您在屏幕截图中提供的文档,数组中的 input_data 嵌套级别不应存在

$data = [
  'request' => [
    'subject' => $notification->subject,
    'description' => $notification->description,
    'status' => ['name' => 'Open']
  ]
]);

我设法找到了解决方案,如下所示,

private function openTicket($notification): bool
    {
        $data = json_encode(['request' => ['subject' => $notification->subject,
            'description' => $notification->description,
            'status' => ['name' => 'Open']]]);

        $request_id = $notification->request_id;
        $response = Http::withHeaders([
            'technician_key' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
            'Content-Type' => 'application/x-www-form-urlencoded'
        //added asForm() before put
        ])->asForm()->put('http://localhost:8082/api/v3/requests/' . $request_id, [
            'input_data' => $data
        ]);
      
        if ($response->status() == 200) {
            return true;
        }
        return false;
    }

我在 put 函数之前添加了 asForm() 。这是因为 asForm() 表示请求包含表单参数。我还修改了

中的 $data 对象
$data = json_encode(['input_data' => ['request' => ['subject' => $notification->subject,
            'description' => $notification->description,
            'status' => ['name' => 'Open']]]]);

$data = json_encode(['request' => ['subject' => $notification->subject,
            'description' => $notification->description,
            'status' => ['name' => 'Open']]]);

然后它如我所料的那样工作了。