无法通过 CHttpFile 添加请求标头 - C++/MFC

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

我想在以下代码片段中使用标头“Authorization:bearer”调用API方法“get”。我检查并发现函数“addRequestHeader”的返回值是true,但是在调用“sendRequest()”之后,我收到的值“strResponse”为

"{\"message\":\"Missing Authorization header\",\"status\":401}"
这是我的职能:

CString GetAvailableSymbols(void)
{
    CString oResult = "";

    // Create a HTTP session
    CInternetSession session(AGENT_NAME);

    // Create a HTTP connection
    CHttpConnection* pConnection = session.GetHttpConnection(_T("fc-data.ssi.com.vn"));

    // Create a HTTP request
    CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, _T("/api/v2/Market/Securities?pageIndex=1&pageSize=10&market=hose"));

    // Send the request with custom headers
    const TCHAR szHeaders[] = _T("Authorization: Bearer TestToken\r\nAccept: application/json\r\nUser-Agent:HttpClient\r\n");
    bool test = pFile->AddRequestHeaders(szHeaders);
    BOOL bSend = pFile->SendRequest();

    // Receive the response
    CString strResponse;
    char szBuffer[1024];
    UINT nRead;
    while ((nRead = pFile->Read(szBuffer, sizeof(szBuffer))) > 0)
    {
        szBuffer[nRead] = '\0';
        strResponse += szBuffer;
    }

    // Close the file
    pFile->Close();
    delete pFile;

    // Close the connection
    session.Close();

    // Parse the response to extract symbols
    // Here, you should parse the JSON response to extract symbols
    // For simplicity, let's assume the symbols are extracted correctly
    int nIndex = strResponse.Find("\"Symbol\": \"");
    while (nIndex != -1)
    {
        CString strSymbol = strResponse.Mid(nIndex + 11); // Extracting symbol starting from after "\"Symbol\": \""
        strSymbol = strSymbol.SpanExcluding("\""); // Removing everything after the symbol value
        oResult += strSymbol + "\n";

        nIndex = strResponse.Find("\"Symbol\": \"", nIndex + 1); // Find next occurrence of symbol
    }

    return oResult;
}
c++ http visual-c++ mfc
1个回答
0
投票

我已经解决了这个问题,发送这样的请求时我必须附加标头

pFile->SendRequest(strHeaders, lpFormData, strFormData.GetLength());
© www.soinside.com 2019 - 2024. All rights reserved.