使用 C 的原始 libcurl JSON PUT 请求

2023-12-22

我目前正在编写一个类似 REST 的客户端,只需要执行 PUT 请求。

Problem:
运行该程序并没有在 URL 的 API 上给出正确的结果,我不知道为什么。

使用curl_easy_perform(curl)在调用时不会抛出错误。但 URL 的 API 上并未生成预期结果。

使用curl_easy_send(curl,..,..,..) 抛出:不支持的协议错误

假设:
我假设我使用curl_easy_opts的顺序有问题?我什至错过了几行关键行?

我一直在这里阅读其他人如何执行 PUT 请求并一直在使用他们的方法。

计划摘要:

我的程序提示用户输入一些字符串/字符数据,然后我自己构建字符串,例如标头和有效负载。标头和有效负载均为 JSON 格式,但有效负载只是一个字符串(在本例中为 char *str = (char *)mallo.. 等)。标头的构造方式如下所示。

我的标头正在使用构建

struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
//there is more content being appended to the header

CURL 函数调用:

    //init winsock stuff
    curl_global_init(CURL_GLOBAL_ALL);

    //get a curl handle
    curl = curl_easy_init();

if(curl){
    //append the headers
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    //specify the target URL
    curl_easy_setopt(curl, CURLOPT_URL, url);

    //connect ( //i added this here since curl_easy_send() says it requires it. )
    curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY,1L); 

    //specify the request (PUT in our case)
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");

    //append the payload
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);

    res = curl_easy_perform(curl);
    //res = curl_easy_send(curl, payload, strlen(payload),&iolen);

    //check for errors
    if(res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

    curl_easy_cleanup(curl);
}

你不应该使用CURLOPT_CONNECT_ONLY选项或curl_easy_send()函数,这些旨在用于自定义的非 HTTP 协议。

See 这一页 http://curl.haxx.se/libcurl/c/httpput.html有关如何使用 libcurl 执行 PUT 请求的示例。基本上,您想要启用CURLOPT_UPLOAD and CURLOPT_PUT选项表示您正在执行 PUT 请求并允许上传带有请求的正文,然后您设置CURLOPT_READDATA and CURLOPT_INFILESIZE_LARGE告诉 libcurl 如何读取您正在上传的数据以及数据有多大的选项。

在您的情况下,如果内存中已经有数据,那么您不需要从文件中读取它,您可以memcpy()它在你的读取回调中。

复制的示例代码如下:

/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected] /cdn-cgi/l/email-protection>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at http://curl.haxx.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ***************************************************************************/ 
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <curl/curl.h>

/*
 * This example shows a HTTP PUT operation. PUTs a file given as a command
 * line argument to the URL also given on the command line.
 *
 * This example also uses its own read callback.
 *
 * Here's an article on how to setup a PUT handler for Apache:
 * http://www.apacheweek.com/features/put
 */ 

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
  size_t retcode;
  curl_off_t nread;

  /* in real-world cases, this would probably get this data differently
     as this fread() stuff is exactly what the library already would do
     by default internally */ 
  retcode = fread(ptr, size, nmemb, stream);

  nread = (curl_off_t)retcode;

  fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T
          " bytes from file\n", nread);

  return retcode;
}

int main(int argc, char **argv)
{
  CURL *curl;
  CURLcode res;
  FILE * hd_src ;
  struct stat file_info;

  char *file;
  char *url;

  if(argc < 3)
    return 1;

  file= argv[1];
  url = argv[2];

  /* get the file size of the local file */ 
  stat(file, &file_info);

  /* get a FILE * of the same file, could also be made with
     fdopen() from the previous descriptor, but hey this is just
     an example! */ 
  hd_src = fopen(file, "rb");

  /* In windows, this will init the winsock stuff */ 
  curl_global_init(CURL_GLOBAL_ALL);

  /* get a curl handle */ 
  curl = curl_easy_init();
  if(curl) {
    /* we want to use our own read function */ 
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

    /* enable uploading */ 
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

    /* HTTP PUT please */ 
    curl_easy_setopt(curl, CURLOPT_PUT, 1L);

    /* specify target URL, and note that this URL should include a file
       name, not only a directory */ 
    curl_easy_setopt(curl, CURLOPT_URL, url);

    /* now specify which file to upload */ 
    curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);

    /* provide the size of the upload, we specicially typecast the value
       to curl_off_t since we must be sure to use the correct data size */ 
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                     (curl_off_t)file_info.st_size);

    /* Now run off and do what you've been told! */ 
    res = curl_easy_perform(curl);
    /* Check for errors */ 
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* always cleanup */ 
    curl_easy_cleanup(curl);
  }
  fclose(hd_src); /* close the local file */ 

  curl_global_cleanup();
  return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 C 的原始 libcurl JSON PUT 请求 的相关文章

随机推荐

  • 在 Typescript 中使用“--strictFunctionTypes”有什么好处?

    据我了解 strictFunctionTypesTypescript 中的编译器选项阻止了一个非常常见的多态性用例的工作 type Handler request Request gt Response const myHandler Ha
  • 如何使用Xamarin Android APK的.Net Reactor混淆dll

    我是 Xamarin Android 新手 我使用 Visual Studio 2015 社区版创建了一个应用程序 我已将解决方案配置设置为发布 为了进行混淆 我使用了 Net Reactor 这就是我试图混淆的方式 1 构建应用程序后 我
  • Common-Lisp 以函数格式打印制表符

    我希望打印制表符format功能 我可以通过以下方式实现这一点 C然后放置 tab作为格式的参数 但这似乎有点冗长 因为对于换行符 可以简单地放置一个 在字符串中 使用打印标签最常用的做法是什么format功能 感谢您的帮助 中没有制表符的
  • 在 CrossWalk 中迁移 Cordova 应用程序时出错

    我在尝试着迁移科尔多瓦应用程序 in 人行横道 using 命令行工具如中给出的this https crosswalk project org documentation cordova migrate an application ht
  • 在编译时计算一组常量表达式的最大值

    我试图在 Rust 过程宏 派生宏 内的编译时计算一组常量的最大值 该宏看起来像 fn get max len gt TokenStream Each TokenStream represents a constant expression
  • 有关 mod_rewrite 和 mod_redirect 的帮助

    我的 htaccess 文件是 Redirect 301 http domain com news articles dtMain start 150 http domain com news articles Redirect 301 h
  • 如何使用 pandas read_xml API 读取大型 xml 文件?

    我正在尝试读取一个大的 XML 文件 文件大小约为 84 GB 来自 Post xml 的堆栈溢出数据转储 我注意到有 Pandas API pandas read xml link https pandas pydata org pand
  • 为什么内存块没有被垃圾收集器清理?

    package main import fmt net http runtime func handler w http ResponseWriter r http Request largeMemAlloc make int 100000
  • 创建具有像单例模式一样的可重用性的 CSOM ClientContext

    我在不同的用户操作上调用了多种方法客户端上下文 在每个方法执行上创建它都会导致性能问题 所以我将其添加为静态变量以实现可重用性 性能平均提高了 5 秒 但随后在某些方法中它开始给出随机问题 版本冲突 on 执行查询 但如果我删除静态和空检查
  • 将 GoDaddy 裸域添加到 Heroku 应用程序

    Heroku 自定义域 https devcenter heroku com articles custom domains 我已经设置了two我的 Heroku 应用程序的自定义域 example com example com hero
  • 在 PyTorch 中实现“无限循环”数据集和数据加载器

    我想实现一个无限循环数据集和数据加载器 这是我尝试过的 class Infinite Dataset def len self return HPARAMS batch size return 1 lt lt 30 This causes
  • sprintf 代表什么?

    我尝试在谷歌和维基百科上查找 但找不到答案 有谁知道 sprintf 或 printf 代表什么 是某个东西的缩写吗 Thanks 字符串打印格式 ed IE 使用给定格式打印到字符串
  • 使用匿名类型集合填充 WPF 中的 DataGrid

    我正在使用匿名类型的集合填充数据网格 我正在设置DataGrid s DataContext财产 并且没有错误 数据网格中没有显示任何内容 我尝试对定义的对象集合进行相同的操作 但再次没有显示任何内容 请您指导我该怎么做 Thanks ED
  • 奇怪的“字符串索引超出范围:0”错误

    我有一个巨大的应用程序 在某些时候 当涉及重定向时 我收到了这个奇怪的错误 Caused by java lang StringIndexOutOfBoundsException with message String index out
  • 编写电子邮件嗅探器

    我有兴趣编写一个电子邮件嗅探器 将通过基于网络的客户端发送的所有电子邮件保存到高清 但我不知道如何做到这一点 如何在加密之前捕获 HTTPS 邮件 我真的很感激一些有用的信息 我在网上找不到任何信息 有一个名为 HTTP Analyzer
  • 是否有 shim 或 polyfill 可以解决 Chrome 对数据列表的 512 限制?

    使用绑定到数据列表的输入标签实现了预输入 当用户滚动浏览条目时 Chrome 不会显示第 512 个匹配项之外的任何条目 整个数据列表仅包含大约 950 个条目 使用适用于 Windows 的 Chrome 版本 76 0 3809 100
  • 在大表中查找半径MySQL(纬度经度)内的点的最快方法是什么

    目前我有几个包含 100k 行的表 我正在尝试查找如下数据 SELECT SQRT POW 69 1 latitude 49 1044302 2 POW 69 1 122 801094 longitude COS latitude 57 3
  • ng-click 和 ng-touch 移动设备

    我有一个用 AngularJS 编写的 cordova 移动应用程序 在我的应用程序中添加 ng touch 会使某些 html 行为无法正常工作 此问题的一个示例是 当复选框包装在附有 ng click 的 HTML 元素中时 该复选框不
  • 隐藏的表单元素是否被提交?

    如果 jQuery 的toggle 用于 div 包含表单元素 这些表单元素是否会随表单一起提交 即使它们是隐藏的 我的代码 尽管这个特定问题可能不需要 cms loop title click function ctg this attr
  • 使用 C 的原始 libcurl JSON PUT 请求

    我目前正在编写一个类似 REST 的客户端 只需要执行 PUT 请求 Problem 运行该程序并没有在 URL 的 API 上给出正确的结果 我不知道为什么 使用curl easy perform curl 在调用时不会抛出错误 但 UR