Search code examples
c++jsonhttprequestborland-c++

Send JSON data via HttpOpenRequest


I'm not programming at C++, but i'm asking for someone who does, so i'm sorry if my question is simple or stupid.

I need a simple example of using HttpOpenRequest/HttpSendRequest objects in order to send JSON data to some web service/site.

Thank you


Solution

  • Here is a very bare bones example to send a JSON string to http://hostname/path/scriptname. You will have to add proper error checking, status code checking, etc as needed:

    HINTERNET hInternet = InternetOpen(_T("MyApp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    
    HINTERNET hConnect = InternetConnect(hInternet, _T("hostname"), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
    
    LPTSTR rgpszAcceptTypes[] = {_T("application/json"), NULL};
    HINTERNET hRequest = HttpOpenRequest(hConnect, _T("POST"), _T("/path/scriptname"), NULL, NULL, rgpszAcceptTypes, 0, 0);
    
    HttpAddRequestHeaders(hRequest, _T("Content-Type: application/json\r\n"), -1, HTTP_ADDREQ_FLAG_ADD);
    
    char *JsonData = "..."; // your actual JSON data here
    HttpSendRequest(hRequest, NULL, 0, JsonData, strlen(JsonData))
    
    DWORD StatusCode = 0;
    DWORD StatusCodeLen = sizeof(StatusCode);
    HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &StatusCode, &StatusCodeLen, NULL);
    
    if (StatusCode == 200)
    {
        // use InternetQueryDataAvailable() and InternetReadFile()
        // to read any response data as needed...
    }
    
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hInternet);