Search code examples
visual-c++wininet

how to construct HttpSendRequest method of WININET


I have dummy web service with URI =http://localhost/IO_100_Service.svc/xml?id={id} which return data in XML format I want to call this service using WINInet APi in VC++.Can anybody help me how to use contruct "HttpSendRequest" method to add header and data to call this service .


Solution

  • Here is a sample code you should be able to modify to your needs. I tested it with VS2005 using command line template project.

        #include <tchar.h>
        #include <wininet.h>  
    
        /// ....
    
        HINTERNET hIntSession = 
          ::InternetOpen(_T("MyApp"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    
        HINTERNET hHttpSession = 
          InternetConnect(hIntSession, _T("api.twitter.com"), 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
    
        HINTERNET hHttpRequest = HttpOpenRequest(
          hHttpSession, 
          _T("GET"), 
          _T("1/statuses/user_timeline.xml?screen_name=twitterapi"),
          0, 0, 0, INTERNET_FLAG_RELOAD, 0);
    
        TCHAR* szHeaders = _T("Content-Type: text/html\nMySpecialHeder: whatever");
        CHAR szReq[1024] = "";
        if( !HttpSendRequest(hHttpRequest, szHeaders, _tcslen(szHeaders), szReq, strlen(szReq))) {
          DWORD dwErr = GetLastError();
          /// handle error
        }
    
        CHAR szBuffer[1025];
        DWORD dwRead=0;
        while(::InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer)-1, &dwRead) && dwRead) {
          szBuffer[dwRead] = 0;
          OutputDebugStringA(szBuffer);
          dwRead=0;
        }
    
        ::InternetCloseHandle(hHttpRequest);
        ::InternetCloseHandle(hHttpSession);
        ::InternetCloseHandle(hIntSession);