带有标头和数据的 C++ CURL POST 请求

问题描述 投票:0回答:1

我是 C++ 新手,我正在尝试进行 POST 请求 API 调用。如果有人能指出我做错了什么,我将不胜感激。有问题的功能是“令牌”。

#include <iostream>
#include <string>
#include <fstream>
#include <typeinfo>
#include <curl/curl.h>
#include <cstring>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <curl/curl.h>
#include <stdio.h>

#define SIZE 1000

using namespace std;

const BIO_METHOD* BIO_f_base64(void);

string tokens(string accessCode, string base64Encode) {
    
    CURL* curl = curl_easy_init();
    string readBuffer;

    curl = curl_easy_init();

    if (curl) {

        string json = "{'grant_type':'authorization_code','code':'" + accessCode + "','redirect_uri':'https://127.0.0.1'}";

        struct curl_slist* headers = NULL;

        string authorization("Authorization: Basic ");
        string payload = authorization + base64Encode;
        const char* cstr = payload.c_str();

        headers = curl_slist_append(headers, cstr);
        headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_URL, "https://api.schwabapi.com/v1/oauth/token");

        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 12L);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        curl_easy_perform(curl);

    }
    
    return readBuffer;

}

API 调用似乎已完成,但我收到以下响应:

{"error":"invalid_client","error_description":"Unauthorized"}

c++ api curl post libcurl
1个回答
0
投票

嗯,一方面,您泄漏了 2 个

CURL
对象,因为您调用了
curl_easy_init()
两次,并且根本没有调用
curl_easy_cleanup()

此外,

application/x-www-form-urlencoded
是用于 JSON 的错误媒体类型。请使用
application/json
来代替。

© www.soinside.com 2019 - 2024. All rights reserved.