Hướng dẫn php post data to api - php đăng dữ liệu lên api

Tôi muốn thêm một số suy nghĩ về câu trả lời dựa trên Curl của Fred Tanrikut. Tôi biết hầu hết trong số họ đã được viết trong các câu trả lời ở trên, nhưng tôi nghĩ rằng đó là một ý tưởng tốt để hiển thị một câu trả lời bao gồm tất cả chúng cùng nhau.

Dưới đây là lớp tôi đã viết để thực hiện các yêu cầu http-get/post/put/xóa dựa trên curl, liên quan đến cơ thể phản hồi:

class HTTPRequester {
    /**
     * @description Make HTTP-GET call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPGet($url, array $params) {
        $query = http_build_query($params); 
        $ch    = curl_init($url.'?'.$query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-POST call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPost($url, array $params) {
        $query = http_build_query($params);
        $ch    = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-PUT call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPut($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
    /**
     * @category Make HTTP-DELETE call
     * @param    $url
     * @param    array $params
     * @return   HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPDelete($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
}

Cải tiến

  • Sử dụng http_build_query để lấy chuỗi truy vấn ra khỏi mảng yêu cầu.
  • Trả lời phản hồi thay vì lặp lại nó. BTW Bạn có thể tránh trả lại bằng cách loại bỏ dòng curl_setopt ($ CH, curlopt_returntransfer, true) ;. Sau đó, giá trị trả về là boolean (true = yêu cầu đã thành công nếu không có lỗi xảy ra) và phản hồi được lặp lại. Xem: http://php.net/en/manual/function.curl-exec.phpcurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);. After that the return value is a boolean(true = request was successful otherwise an error occured) and the response is echoed. See: http://php.net/en/manual/function.curl-exec.php
  • Làm sạch phiên đóng và xóa tay cầm curl bằng cách sử dụng curl_close. Xem: http://php.net/manual/en/function.curl-close.phpcurl_close. See: http://php.net/manual/en/function.curl-close.php
  • Sử dụng các giá trị boolean cho hàm Curl_setopt thay vì sử dụng bất kỳ số nào. (Tôi biết rằng bất kỳ số nào không bằng 0 cũng được coi là đúng, nhưng việc sử dụng True tạo ra một mã dễ đọc hơn, nhưng đó chỉ là ý kiến ​​của tôi)curl_setopt function instead of using any number.(I know that any number not equal zero is also considered as true, but the usage of true generates a more readable code, but that's just my opinion)
  • Khả năng thực hiện các cuộc gọi HTTP-PUT/Xóa (hữu ích cho kiểm tra dịch vụ RESTful)

Ví dụ về việc sử dụng

LẤY

$response = HTTPRequester::HTTPGet("http://localhost/service/foobar.php", array("getParam" => "foobar"));

BƯU KIỆN

$response = HTTPRequester::HTTPPost("http://localhost/service/foobar.php", array("postParam" => "foobar"));

ĐẶT

$response = HTTPRequester::HTTPPut("http://localhost/service/foobar.php", array("putParam" => "foobar"));

XÓA BỎ

$response = HTTPRequester::HTTPDelete("http://localhost/service/foobar.php", array("deleteParam" => "foobar"));

Kiểm tra

Bạn cũng có thể thực hiện một số bài kiểm tra dịch vụ thú vị bằng cách sử dụng lớp đơn giản này.

class HTTPRequesterCase extends TestCase {
    /**
     * @description test static method HTTPGet
     */
    public function testHTTPGet() {
        $requestArr = array("getLicenses" => 1);
        $url        = "http://localhost/project/req/licenseService.php";
        $this->assertEquals(HTTPRequester::HTTPGet($url, $requestArr), '[{"error":false,"val":["NONE","AGPL","GPLv3"]}]');
    }
    /**
     * @description test static method HTTPPost
     */
    public function testHTTPPost() {
        $requestArr = array("addPerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPost($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPPut
     */
    public function testHTTPPut() {
        $requestArr = array("updatePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPut($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPDelete
     */
    public function testHTTPDelete() {
        $requestArr = array("deletePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPDelete($url, $requestArr), '[{"error":false}]');
    }
}

Làm thế nào tạo API POST trong PHP?

Tạo một cơ sở dữ liệu và bảng DB. Thiết lập kết nối cơ sở dữ liệu. Tạo tệp API REST. Tạo tệp chỉ mục hoặc HTML ...
Nhận: Đọc hoặc lấy thông tin ..
Bài đăng: Tạo bản ghi mới ..
Đặt: Cập nhật một bản ghi ..
Xóa: Xóa một bản ghi ..

Tôi có thể sử dụng bài đăng để nhận dữ liệu trong API REST không?

Nhận yêu cầu nên được sử dụng để truy xuất dữ liệu khi thiết kế API REST;Các yêu cầu POST nên được sử dụng để tạo dữ liệu khi thiết kế API REST.POST requests should be used to create data when designing REST APIs.

Bài đăng trong cơ sở dữ liệu PHP trong API là gì?

PHP $ _POST là một biến siêu toàn cầu PHP được sử dụng để thu thập dữ liệu biểu mẫu sau khi gửi biểu mẫu HTML với Phương thức = "Post".$ _POST cũng được sử dụng rộng rãi để vượt qua các biến.Ví dụ dưới đây hiển thị một biểu mẫu có trường đầu vào và nút gửi.a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

Làm cách nào để gửi yêu cầu bài đăng dữ liệu?

Để gửi dữ liệu bằng phương thức bài HTTP, bạn phải bao gồm dữ liệu trong phần thân của thông báo bài HTTP và chỉ định loại MIME của dữ liệu với tiêu đề loại nội dung.Dưới đây là một ví dụ về yêu cầu bài HTTP để gửi dữ liệu JSON đến máy chủ.Kích thước và kiểu dữ liệu cho các yêu cầu bài HTTP không bị giới hạn.include the data in the body of the HTTP POST message and specify the MIME type of the data with a Content-Type header. Below is an example of an HTTP POST request to send JSON data to the server. The size and data type for HTTP POST requests is not limited.