如何使用VC进行HTTP连接

  1. CString httpRequest(char* lpHostName, short sPort, char* lpUrl, char* lpMethod, char* lpPostDara, int nPostDataLen)
  2. {
  3.     HINTERNET hInternet, hConnect, hRequest;
  4.     BOOL bRet;
  5.     CString strResponse;

  6.     hInternet = InternetOpen(TEXT("User-Agent:"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
  7.     if (hInternet)
  8.     {
  9.         hConnect = InternetConnect(hInternet, lpHostName, sPort, NULL, TEXT("HTTP/1.1"), INTERNET_SERVICE_HTTP, 0, 0);
  10.         if (hConnect)
  11.         {
  12.             hRequest = HttpOpenRequest(hConnect, lpMethod, lpUrl, TEXT("HTTP/1.1"), NULL, NULL, INTERNET_FLAG_RELOAD, 0);
  13.             if (hRequest)
  14.             {
  15.                 bRet = HttpSendRequest(hRequest, NULL, 0, lpPostDara, nPostDataLen);

  16.                 while (TRUE)
  17.                 {
  18.                     char cReadBuf[4096];
  19.                     unsigned long  lNumOfByteRead;

  20.                     bRet = InternetReadFile(hRequest, cReadBuf, sizeof(cReadBuf)-1, &lNumOfByteRead);
  21.                     if(!bRet || !lNumOfByteRead)
  22.                     {break;}
  23.                     cReadBuf[lNumOfByteRead]=0;
  24.                     strResponse = strResponse + cReadBuf;
  25.                 }
  26.             }
  27.             InternetCloseHandle(hRequest);
  28.         }
  29.         InternetCloseHandle(hConnect);
  30.     }
  31.     InternetCloseHandle(hInternet);

  32.     return strResponse;
  33. }
测试的时候,使用如下代码调用:
CString strResponse = httpRequest("www.hao123.com",80,NULL,"POST",NULL,0);

你可能感兴趣的:(C/C++/Driver)