Unable to add request headers via CHttpFile - C++/MFC

37 views Asked by At

I want to call the API method 'get' with the header 'Authorization: bearer' in the following code snippet. I have checked and found that the return value of the function 'addRequestHeader' is true, but after calling 'sendRequest()', I receive the value 'strResponse' as "{\"message\":\"Missing Authorization header\",\"status\":401}" This is my function:

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;
}
0

There are 0 answers