錯(cuò)誤信息:服務(wù)器返回HTTP/1.1 500 Internal Server Error
環(huán)境:Ubuntu18.04+curl c++庫(kù)
代碼:
#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;
/**錯(cuò)誤代碼
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要在調(diào)用線程中顯式調(diào)用
curl_global_init(CURL_GLOBAL_ALL);
boost::thread post(&httpsPostThread, json_str);
post.join();
curl_global_cleanup();
return 0;
}
原因:按照錯(cuò)誤代碼的方式配置http頭無(wú)法正確配置Content-Type:application/json,導(dǎo)致服務(wù)端不能正確解析json格式的請(qǐng)求body(代碼中的json_str變量)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者