Để gửi dữ liệu dưới dạng tải trọng thô JSON trong yêu cầu HTTP bằng Laravel, bạn có thể sử dụng phương pháp json của mặt tiền Http. Đây là một ví dụ. use Illuminate\Support\Facades\Http; // Set up the data to send as a JSON payload $data = [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ]; // Send a POST request with a JSON payload $response = :withHeaders([ 'Content-Type' => 'application/json', ])->post('//example.com/api/endpoint', $data); // Get the response status code $statusCode = $response->status(); // Get the response body $body = $response->json();
Bạn cũng có thể sử dụng phương thức postJson của mặt tiền Http để gửi tải trọng JSON trong yêu cầu POST. Phương pháp này sẽ tự động đặt tiêu đề Content-Type thành application/json. use Illuminate\Support\Facades\Http; // Set up the data to send as a JSON payload $data = [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ]; // Send a POST request with a JSON payload $response = :postJson('//example.com/api/endpoint', $data); // Get the response status code $statusCode = $response->status(); // Get the response body $body = $response->json();
Bạn cũng có thể sử dụng các phương thức putJson, use Illuminate\Support\Facades\Http; // Set up the data to send as a JSON payload $data = [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ]; // Send a POST request with a JSON payload $response = :postJson('//example.com/api/endpoint', $data); // Get the response status code $statusCode = $response->status(); // Get the response body $body = $response->json();0 và use Illuminate\Support\Facades\Http; // Set up the data to send as a JSON payload $data = [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ]; // Send a POST request with a JSON payload $response = :postJson('//example.com/api/endpoint', $data); // Get the response status code $statusCode = $response->status(); // Get the response body $body = $response->json();1 để gửi tải trọng JSON trong các yêu cầu PUT, PATCH và DELETE tương ứng
Hãy nhớ rằng mặt tiền Http chỉ là một cách thuận tiện để gửi các yêu cầu HTTP trong Laravel. Bạn cũng có thể sử dụng các thư viện khác như Guheads để gửi các yêu cầu HTTP với tải trọng JSON
Làm cách nào để đăng dữ liệu JSON trong laravel?
Làm cách nào để gửi phản hồi ở định dạng JSON trong laravel?
Có thể gửi phản hồi JSON bằng phương thức json . Phương pháp này sẽ tự động đặt tiêu đề Kiểu nội dung thành ứng dụng/json. Phương thức json sẽ tự động chuyển đổi mảng thành phản hồi json phù hợp.
Làm cách nào để mã hóa JSON trong laravel?
Làm cách nào để đặt mã trạng thái http trong laravel?
Bạn có thể sử dụng http_response_code() để đặt mã phản hồi HTTP . Nếu bạn không nhập tham số nào thì http_response_code sẽ lấy mã trạng thái hiện tại. Nếu bạn truyền một tham số, nó sẽ đặt mã phản hồi. Lưu câu trả lời này.