【问题标题】:How to send JSON data to a REST API?如何将 JSON 数据发送到 REST API?
【发布时间】:2019-06-18 16:12:55
【问题描述】:

我正在向 Wordpress 站点发送数据,该站点使用 C++ 中的 libcurl 和 WooCommerce REST API 安装了 WooCommerce 插件。数据似乎已发送,但网站上未显示预期结果。它的目的是更新(修改)产品。我的代码基于 WooCommerce 文档,找到 here

我已经设法从程序中的一个单独的 txt 文件中获取了 CURLOPT_VERBOSE 文本。

这是我使用 cURL 的 C++ 代码:

std::string URL = main_domain + "wp-json/wc/v3/products/" + product_id + "?consumer_key=" + consumer_key + "&consumer_secret=" + consumer_secret;
    curl_slist* headers = NULL;
    headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
    headers = curl_slist_append(headers, "Accept:application/json");
    headers = curl_slist_append(headers, "Content-Type:application/json");
    headers = curl_slist_append(headers, "charsets: utf-8");

    // log file
    FILE* filep = fopen("logfichier.txt", "w");

    std::string toUpdate = "{\"id\":\"" + product_id + ",\"name\":\"" + product_name + "\",\"description\":\"" + product_description + "\",\"price\":\"" + product_price + "\"}";

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if (curl) {
        readBuffer = "";
        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); 
        curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, toUpdate.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, toUpdate.length());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
        curl_easy_setopt(curl, CURLOPT_STDERR, filep);
        res = curl_easy_perform(curl);

        // Check for errors
        if (res != CURLE_OK) {
            // error handling and cleanup           
        }
        else {
            // code and cleanup
        }

    }
    else {
        // error handling and cleanup
    }

我确实将在互联网上找到的每个标题都与我试图在我的代码中完成的内容相关。 这是返回的调试文本:

* STATE: INIT => CONNECT handle 0x10870278; line 1428 (connection #-5000)
* Added connection 0. The cache now contains 1 members
* STATE: CONNECT => WAITRESOLVE handle 0x10870278; line 1464 (connection #0)
*   Trying 192.XX.XX.XX...
* TCP_NODELAY set
* STATE: WAITRESOLVE => WAITCONNECT handle 0x10870278; line 1545 (connection #0)
* Connected to mywebsite.com (192.XX.XX.XX) port 443 (#0)
* STATE: WAITCONNECT => SENDPROTOCONNECT handle 0x10870278; line 1599 (connection #0)
* Marked for [keep alive]: HTTP default
* schannel: SSL/TLS connection with mywebsite.com port 443 (step 1/3)
* schannel: checking server certificate revocation
* schannel: sending initial handshake data: sending 176 bytes...

// (here was just a bunch of connexion attemps log text...)

* schannel: SSL/TLS handshake complete
* schannel: SSL/TLS connection with mywebsite.com port 443 (step 3/3)
* schannel: stored credential handle in session cache
* STATE: PROTOCONNECT => DO handle 0x10870278; line 1634 (connection #0)
> PUT /wp-json/wc/v3/products/111867?consumer_key=(the actual key)&consumer_secret=(the actual secret) HTTP/1.1

Host: mywebsite.com

Transfer-Encoding: chunked

Accept:application/json

Content-Type:application/json

charsets: utf-8


4b

* upload completely sent off: 82 out of 75 bytes
* STATE: DO => DO_DONE handle 0x10870278; line 1696 (connection #0)
* STATE: DO_DONE => WAITPERFORM handle 0x10870278; line 1823 (connection #0)
* STATE: WAITPERFORM => PERFORM handle 0x10870278; line 1838 (connection #0)
* schannel: client wants to read 16384 bytes
* schannel: encdata_buffer resized 17408
* schannel: encrypted data buffer: offset 0 length 17408

// (a few decrypting data attempts...)

* schannel: decrypted data returned 536
* schannel: decrypted data buffer: offset 0 length 16384
* HTTP 1.1 or later with persistent connection, pipelining supported
< HTTP/1.1 200 OK

< Date: Tue, 18 Jun 2019 15:27:42 GMT

* Server Apache is not blacklisted
< Server: Apache

< X-Robots-Tag: noindex

< Link: <https://mywebsite.com/wp-json/>; rel="https://api.w.org/"

< X-Content-Type-Options: nosniff

< Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages

< Access-Control-Allow-Headers: Authorization, Content-Type

< Expires: Wed, 11 Jan 1984 05:00:00 GMT

< Cache-Control: no-transform, no-cache, must-revalidate, max-age=0

< Allow: GET, POST, PUT, PATCH, DELETE

< Transfer-Encoding: chunked

< Content-Type: application/json; charset=UTF-8

< 

* schannel: client wants to read 16384 bytes
* schannel: encrypted data buffer: offset 835 length 17408

// (a few decrypting data attempts...)

* schannel: decrypted data returned 1986
* schannel: decrypted data buffer: offset 0 length 16384
* STATE: PERFORM => DONE handle 0x10870278; line 2011 (connection #0)
* multi_done
* Connection #0 to host axanti.info left intact

我从原文中去掉了一些多余的部分,保留了我认为是主要信息的部分。似乎我的 JSON 数据实际上已发送到服务器,但预期的结果并未显示在我的网站上(应该修改产品,但实际上没有)。 这段代码有什么错误的吗?还是服务器端的问题?因为我几乎应用了官方文档中提到的相同内容。

【问题讨论】:

    标签: c++ curl woocommerce libcurl put


    【解决方案1】:

    如果关闭,看起来像您的有效载荷。 id 部分是多余的,因为您已经通过 URL 指定要更新的产品,因此您可以删除它。此外,您试图错误地设置价格。根据 REST 文档,您需要使用 regular_price 属性而不是 priceprice 是只读的)。正确的有效载荷应如下所示:

    {
        name: 'My product name',
        description: 'my product description',
        regular_price' : '3.50',
    }
    

    【讨论】:

    • 感谢您的帮助,我已删除 id 部分并将 price 更改为 regular_price。我已经在 Insomnia 中尝试过你的方法,它的效果很好,尽管我的 C++ 程序中似乎仍然存在这个问题。它让我认为我可能错误地配置了我的 CURL 选项。你有什么其他想法 CURL 设置参数可能是错误的吗?
    • 我可以尝试提供一些帮助。我通常在 PHP 中执行此操作,并使用他们提供的 Woocommerce 库为我管理 cURL 提交。我没有看到的唯一 cURL 选项是 CURLOPT_RETURNTRANSFER。您需要使用它来验证提交,因为 Woocommerce 将返回更新的产品数据,并将收到的任何错误发回。
    • 这个选项只存在于 PHP 中,我也在网上听说过。 C 等效项是CURLOPT_WRITEFUNCTIONCURLOPT_WRITEDATA,写在readBuffer 变量中。我这样做的方式是 MessgeBox 显示来自服务器对每个请求的响应。现在,服务器给我一个带有产品的 JSON 字符串,但它是旧参数。我的 WooCommerce 库存中的参数也不会改变。
    • 不幸的是,我不太精通 C++ 的 cURL。如果您确实能够通过 Insomnia 进行操作并且这些更改仍然存在,那么它可能与您的 cURL 配置有关。如果这些更改在 Insomnia 中没有持续存在,请检查以确保您的 API 凭据是可读写的。一个很长的想法可能是您的 cURL 响应/请求正在以某种方式被缓存?
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2019-10-09
    • 2020-06-22
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多