c - 使用 libcurl 在 PUT 请求中发送字符串

标签 c curl

我的代码是这样的:

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers, client_id_header);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1/test.php");  
    curl_easy_setopt(curl, CURLOPT_PUT, 1L);

    res = curl_easy_perform(curl);
    res = curl_easy_send(curl, json_struct, strlen(json_struct), &io_len);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}

这是行不通的,程序永远挂起。

在 test.php 中,这些是我得到的请求 header :

array(6) {
  ["Host"]=>
  string(9) "127.0.0.1"
  ["Accept"]=>
  string(3) "*/*"
  ["Transfer-Encoding"]=>
  string(7) "chunked"
  ["X-ClientId"]=>
  string(36) "php_..."
  ["Content-Type"]=>
  string(16) "application/json"
  ["Expect"]=>
  string(12) "100-continue"
}

但是正文是空的,意味着请求没有发送json数据。

我想用 libcurl 做的实际上就是这些命令行脚本:

curl -X PUT -H "Content-Type: application/json" -d '... some json ...' 127.0.0.1/test.php

最佳答案

明白了:)

不要使用

curl_easy_setopt(curl, CURLOPT_PUT, 1L);

发出自定义请求并将数据作为 POSTFIELDS 发送:

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers, client_id_header);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_URL, request_url);  
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */

    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_struct); /* data goes here */

    res = curl_easy_perform(curl);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}

关于c - 使用 libcurl 在 PUT 请求中发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7569826/

相关文章:

c - 如何正确解决指针对齐增加的问题?

bash - 如何为 curl 命令对数据进行 urlencode?

ubuntu - 使用 curl 测试 Bottle api

mysql - Windows 8.1 上 MySQL 的 CodeBlocks 链接器问题

c - 如何确定Pi(π)的准确度

c - 函数不更新 int 字段

linux - curl nss 错误 -5938

flutter - 如何在flutter中将curl命令转换为http请求?

php - Curl 在执行 POST 到 https 时挂起我的 apache 服务器

python - 在 C 中嵌入 Python : Passing a two dimensional array and retrieving back a list