从C代码调用DynamoDB低级API时出错

时间:2016-05-25 10:52:00

标签: c amazon-web-services curl amazon-dynamodb libcurl

我试图从C代码调用DynamoDB低级API。这是我的代码

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


int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    struct curl_slist *chunk = NULL;

    chunk = curl_slist_append(chunk, "Host: dynamodb.us-east-1.amazonaws.com;");    
    chunk = curl_slist_append(chunk, "Accept-Encoding: identity;");
    chunk = curl_slist_append(chunk, "Content-Length: 53;");    
    chunk = curl_slist_append(chunk, "User-Agent: CustomApp42;");
    chunk = curl_slist_append(chunk, "Content-Type: application/x-amz-json-1.0;");
    chunk = curl_slist_append(chunk, "Authorization: AWS4-HMAC-SHA256 Credential=<Credential>, SignedHeaders=<Headers>, Signature=<signature>;");   
    chunk = curl_slist_append(chunk, "X-Amz-Date: 4.4.2016 ;");
    chunk = curl_slist_append(chunk, "X-Amz-Target: DynamoDB_20120810.GetItem;");

    res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

    curl_easy_setopt(curl, CURLOPT_URL, "dynamodb.us-east-1.amazonaws.com");
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"TableName\":\"Pets\",\"Key\":{\"AnimalType\":{\"S\": \"Dog\"},\"Name\": {\"S\": \"Fido\"}}}");
    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);

    /* free the custom headers */ 
    curl_slist_free_all(chunk);
  }
  return 0;
}

但是在运行时会产生错误

HTTP/1.1 400 Bad Request

我主要面对两个问题。

  1. 我有aws_access_key_id和aws_secret_access_key。如何使用这两个凭证创建授权(SignedHeaders&amp; Signature)?
  2. 如何修改发电机查询方法的“X-Amz-Target”?

1 个答案:

答案 0 :(得分:0)

您是否可以使用AWS SDK for C++?它将为您完成所有这些繁重的工作。实际上,即使您正在制作C程序,也可以将extern C library结构公开给您需要的AWS SDK调用。因此,无论哪种方式,我建议使用AWS SDK for C ++进行编码,并创建一个extern C库包装器,以防您需要将主程序编译为C程序。