【问题标题】:RESTful client in cc中的RESTful客户端
【发布时间】:2014-12-18 05:14:02
【问题描述】:

您好,我想对远程服务器进行 RESTful 调用。 网址是http://bulksms.net/API.svc/sms/json/sendmessage?username=newuser&password=newpasswd&msg=test&msisdn=9999999999&tagname=Demo&shortcode=8888&telcoId=5&dnRequired=false 服务器文档说:

Parameters

字符串用户名、字符串密码、字符串 msg、字符串 msisdn、字符串标记名、字符串短代码、int telcoId、bool dnRequired

返回值 API 将返回包含三个成员的对象 成功 信息 唯一标识

我在 c 中制作了一个示例客户端,但它无法正常工作。下面是我的代码。

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

int main(int argc, char *argv[])
{
  CURL *curl;
  char url[80];
  CURLcode res;

  strcpy(url,"http://bulksms.net/API.svc/sms/json/sendmessage?username=newuser&password=newpasswd&msg=test&msisdn=9999999999&tagname=Demo&shortcode=8888&telcoId=5&");

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_POST, url);

    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
  }
  return 0;
}

输出:

【问题讨论】:

  • msd 输出以写入

    要求长度


    HTTP 错误 411。请求必须分块或具有内容长度。

  • 仅供参考,该字符串超过 80 个字符(它更像是 150 个字符,包括终止符)。因此,您的 strcpy 会调用未定义的行为,并且您的程序格式错误
  • 甚至更好 - strdup(但请记住释放结果)
  • 将索引数组更改为 char url[] 但错误仍然相同----

    HTTP 错误 411。请求必须分块或具有内容长度。

    。我想我必须添加一些与 RESTfull 相关的内容

标签: c http restful-url


【解决方案1】:

我解决了这个问题。实际上,在 RESTful POST 方法中,url 和数据应该部分添加。下面是 RESTfull POST 方法在 c 中的成功客户端。

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

int main(int argc, char *argv[])
{
  CURL *curl;
  CURLcode res;
  char url[]= "http://bulksms.net/API.svc/sms/json/sendmessage";
  char postData[] = "username=newuser&password=newpasswd&msg=test&msisdn=9999999999&tagname=Demo&shortcode=8888&telcoId=5&dnRequired=false";
  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
  }
  return 0;
}

【讨论】:

    【解决方案2】:

    您的 strcpy 函数会导致未定义的行为,因为您有 80 个字符的缓冲区并且源字符串比它更多。

    试试这样的。

    char url[]="http://bulksms.net/API.svc/sms/json/sendmessage?username=newuser&password=newpasswd&msg=test&msisdn=9999999999&tagname=Demo&shortcode=8888&telcoId=5&";
    

    您可以使用strncpysnprintf 进行安全复制并避免未定义的行为。

    【讨论】:

    • 删除了索引数组并使用了 char url[],但这并没有阻止错误。 ----

      HTTP 错误 411。请求必须分块或具有内容长度。

    • @JYOTIRANJANPANDA:注意那个错误信息。您的请求需要分块或设置内容长度...
    【解决方案3】:

    与基于 SOAP 的 Web 服务不同,RESTful Web API 没有“官方”标准。这是因为 REST 是一种架构风格,而 SOAP 是一种协议。尽管 REST 本身不是标准,但大多数 RESTful 实现都使用 HTTP、URI、JSON 和 XML 等标准。

    【讨论】:

      【解决方案4】:

      我知道这是一个迟来的答案,但是有一个完整且很棒的库可以让您通过 C/C++ 引入您的 restful api。适用于 Linux、Freebsd 和 Windows(可能还有更多操作系统)

      githubhttps://github.com/babelouest/ulfius

      【讨论】:

        猜你喜欢
        • 2013-09-16
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 2016-07-17
        • 2012-02-27
        • 2023-03-13
        • 1970-01-01
        • 2012-05-16
        相关资源
        最近更新 更多