美文网首页
ubuntu使用curl库以POST方式发送JSON数据

ubuntu使用curl库以POST方式发送JSON数据

作者: Joker64 | 来源:发表于2021-02-01 15:40 被阅读0次

错误信息:服务器返回HTTP/1.1 500 Internal Server Error

环境:Ubuntu18.04+curl c++库

代码:

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

#include <boost/thread/thread.hpp>

using json = nlohmann::json;
size_t getResCallback(char* ptr, size_t size, size_t nmemb, void* userdata) {
  long sizes = size * nmemb;

  char* recv = new char[sizes];
  memcpy(recv, (char*)ptr, sizes);
  printf("Data Received:\n %s\n", recv);
  return sizes;
}
void httpsPostThread(std::string& json_str) {
  CURLcode res;
  CURL* curl_post_handler = nullptr;
  curl_post_handler = curl_easy_init();
  struct curl_slist* headers = nullptr;
/**错误代码
curl_slist_append(headers, "Accept: application/json");
curl_slist_append(headers, "Content-Type:application/json");
curl_slist_append(headers, "charset=utf-8");
**/
  headers = curl_slist_append(headers, "Accept: application/json");
  headers = curl_slist_append(headers, "Content-Type:application/json");
  headers = curl_slist_append(headers, "charset=utf-8");

  if (curl_post_handler) {
    curl_easy_setopt(
        curl_post_handler, CURLOPT_URL,
        "htpp://some/u/r/l");
    curl_easy_setopt(curl_post_handler, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl_post_handler, CURLOPT_POSTFIELDS, json_str.c_str());
    curl_easy_setopt(curl_post_handler, CURLOPT_POSTFIELDSIZE,
                     json_str.length());
    curl_easy_setopt(curl_post_handler, CURLOPT_WRITEFUNCTION, getResCallback);
    curl_easy_setopt(curl_post_handler, CURLOPT_VERBOSE, 1L);
    res = curl_easy_perform(curl_post_handler);
    if (res != CURLE_OK) {
      printf("curl post easy perform error res = %d \n", res);
      return;
    }
    curl_easy_cleanup(curl_post_handler);
    return;
  }
}
int main(int argc, char const* argv[]) {
  std::string json_str =
      "{\"login\":\"someone\", "
      "\"password\":\"123456\"}";
  //curl_global_init 和curl_global_cleanup要在调用线程中显式调用
    curl_global_init(CURL_GLOBAL_ALL);
    boost::thread post(&httpsPostThread, json_str);
    post.join();
    curl_global_cleanup();
    return 0;
}

原因:按照错误代码的方式配置http头无法正确配置Content-Type:application/json,导致服务端不能正确解析json格式的请求body(代码中的json_str变量)

解决方案:Lukasa@StackOverflow的回答

相关文章

网友评论

      本文标题:ubuntu使用curl库以POST方式发送JSON数据

      本文链接:https://www.haomeiwen.com/subject/wvojtltx.html