sanjayan ravi
sanjayan ravi

Reputation: 143

REST API to connect a online REST server

I am trying to write a REST API to connect to an online REST server. Unfortunately, I am not able to connect to the server and end up getting an error message saying "Method Not Allowed". I already tested the POST method on the online REST server using a REST API plugin from the web browser and method was accepted and the test was successful but I do not understand why my application is failing. I was wondering if anyone would be kind enough to guide me in the right direction. Thank you.

    CInternetSession session(_T("MySession"));
    CHttpConnection* pServer = NULL;
    CHttpFile* pFile = NULL;
    char *szBuff = new char[500];
    CString strServerName = _T("rest.cleverreach.com");
    CString headers = _T("Content-Type: application/x-www-form-urlencoded\r\n");
    headers += _T("Host: rest.cleverreach.com\r\n");
    headers += _T("Method: POST\r\n");
    headers += _T("Pragma: no-cache\r\n");
    headers += _T("Keep-Alive: true\r\n");
    headers += _T("Accept-Language: en-US\r\n");
    CString szHeaders = headers;
    DWORD dwRet;
    CString strObject = _T("/v2/login.json");
    INTERNET_PORT nPort = INTERNET_DEFAULT_HTTP_PORT;
    CString parameters;
    parameters = "client_id=123456&[email protected]&password=blahblahblah";
    try
    {
        pServer = session.GetHttpConnection(strServerName, nPort, NULL, NULL);
        pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
        pFile->AddRequestHeaders(szHeaders);
        pFile->SendRequest(szHeaders, szHeaders.GetLength(), &parameters, parameters.GetLength());
        pFile->QueryInfoStatusCode(dwRet);
        pFile->Read(szBuff, 500);
        CString tempSzBuff = CString(szBuff);
        _tprintf_s(tempSzBuff);     
    }
    catch (CInternetException *e)
    {
        TCHAR sz[1024];
        e->GetErrorMessage(sz, 1024);
        _tprintf_s ((_T("ERROR!  %s\n"), sz));
        e->Delete();
    }

Result :

{"error":{"code":405,"message":"Method Not Allowed"}

Upvotes: 0

Views: 374

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31659

CString parameters;
...
pFile->SendRequest(szHeaders, szHeaders.GetLength(), &parameters, parameters.GetLength());

The third parameter in SendRequest is LPVOID, it expects characters usually in ASCII or UTF8 format. Don't pass the address of &parameters. You can use CString::GetBuffer

In ANSI, use

pFile->SendRequest(szHeaders, szHeaders.GetLength(), 
    parameters.GetBuffer(), parameters.GetLength());
parameters.ReleaseBuffer();

If UNICODE is defined, convert to UTF8

CStringA copy = CW2A(parameters, CP_UTF8);
pFile->SendRequest(szHeaders, szHeaders.GetLength(), 
    copy.GetBuffer(), parameters.GetLength());
copy.ReleaseBuffer();

pFile needs to be cleaned up as well.

See also SendRequest

Upvotes: 1

Related Questions