使用WinINet和WinHTTP实现Http访问

Http访问有两种方式,GET和POST,就编程来说GET方式相对简单点,它不用向服务器提交数据,在这个例程中我使用POST方式,提交数据value1与value2,并从服务器得到他们的和(value1 + value2)。

为实现Http访问,微软提供了二套API:WinINet, WinHTTP。WinHTTP比WinINet更加安全和健壮,可以这么认为WinHTTP是WinINet的升级版本。这两套API包含了很多相似的函数与宏定义,呵呵,详细对比请查阅msdn中的文章“Porting WinINet Applications to WinHTTP”,在线MSDN连接:http://msdn2.microsoft.com/en-us/library/aa384068.aspx。在这个例程中,通过一个宏的设置来决定是使用WinHttp还是WinINet。代码如下:

#define USE_WINHTTP      //Comment this line to user wininet.

 

下面来说说实现Http访问的流程(两套API都一样的流程):

1, 首先我们打开一个Session获得一个HINTERNET session句柄;

2, 然后我们使用这个session句柄与服务器连接得到一个HINTERNET connect句柄;

3, 这样我们使用这个connect句柄来打开Http 请求得到一个HINTERNET request句柄;

4, 这样我们就可以使用这个request句柄来发送数据与读取从服务器返回的数据;

5, 最后依次关闭request,connect,session句柄。

在这个例程中以上各个流程都进行了简单封装,以便对比两套API函数的些许差异。下面让源代码说话,原工程是一个windows控制台工程,你可以很容易通过拷贝代码重建工程。

另:如果你从服务器得到的返回数据是utf8格式的文本数据,你将需要对返回的数据进行转换才能争取显示(中文,日文等)。仅供参考,转换为ATL CStringW的函数见下:

 

CStringW GetStringWFromUtf8(const std::string& str)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), int(str.length()), 0, 0);

    CStringW buf;
    WCHAR*    dd = buf.GetBuffer(len);

    len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), int(str.length()), dd, len);

    buf.ReleaseBuffer(len);

    return buf;
}
完整代码如下:

// HttpPost.cpp written by [email protected]
// 2007/11/30
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
#include <atlbase.h>
#include <atlstr.h>
#define USE_WINHTTP    //Comment this line to user wininet.
#ifdef USE_WINHTTP
    #include <winhttp.h>
    #pragma comment(lib, "winhttp.lib")
#else
    #include <wininet.h>
     #pragma comment(lib, "wininet.lib")
#endif
#define BUF_SIZE    (1024)

// CrackedUrl
 class CrackedUrl {
    int m_scheme;
    CStringW m_host;
     int m_port;
    CStringW m_path;
 public:
    CrackedUrl(LPCWSTR url)
    {
     URL_COMPONENTS uc = { 0};
       uc.dwStructSize = sizeof(uc);
       const DWORD BUF_LEN = 256;
       WCHAR host[BUF_LEN];
        uc.lpszHostName = host;
         uc.dwHostNameLength = BUF_LEN;
         WCHAR path[BUF_LEN];
        uc.lpszUrlPath = path;
        uc.dwUrlPathLength = BUF_LEN;
        WCHAR extra[BUF_LEN];
       uc.lpszExtraInfo = extra;
        uc.dwExtraInfoLength = BUF_LEN;
 
 #ifdef USE_WINHTTP
        if (!WinHttpCrackUrl(url, 0, ICU_ESCAPE, &uc)) {
             printf("Error:WinHttpCrackUrl failed!/n");
        }
#else
        if (!InternetCrackUrl(url, 0, ICU_ESCAPE, &uc)) {
            printf("Error:InternetCrackUrl failed!/n");
        }
#endif
       m_scheme = uc.nScheme;
        m_host = host;
        m_port = uc.nPort;
        m_path = path;
    }
     int GetScheme() const
    {
       return m_scheme;
    }
     LPCWSTR GetHostName() const
     {
         return m_host;
    }

     int GetPort() const
   {
        return m_port;
    }
   LPCWSTR GetPath() const
    {
         return m_path;
    }
    static CStringA UrlEncode(const char* p)
    {
         if (p == 0) {
            return CStringA();
        }
       CStringA buf;

        for (;;) {
            int ch = (BYTE) (*(p++));
            if (ch == '/0') {
                 break;
            }

            if (isalnum(ch) || ch == '_' || ch == '-' || ch == '.') {
               buf += (char)ch;
            }
            else if (ch == ' ') {
                buf += '+';
            }
            else {
                char c[16];
               wsprintfA(c, "%%%02X", ch);
                buf += c;
            }
        }

        return buf;
    }
};
// CrackedUrl
HINTERNET OpenSession(LPCWSTR userAgent = 0)
{
#ifdef USE_WINHTTP
    return WinHttpOpen(userAgent, NULL, NULL, NULL, NULL);;
#else
    return InternetOpen(userAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
#endif
}
HINTERNET Connect(HINTERNET hSession, LPCWSTR serverAddr, int portNo)
{
#ifdef USE_WINHTTP
    return WinHttpConnect(hSession, serverAddr, (INTERNET_PORT) portNo, 0);
#else
    return InternetConnect(hSession, serverAddr, portNo, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
#endif
}
HINTERNET OpenRequest(HINTERNET hConnect, LPCWSTR verb, LPCWSTR objectName, int scheme)
{
    DWORD flags = 0;
#ifdef USE_WINHTTP
    if (scheme == INTERNET_SCHEME_HTTPS) {
        flags |= WINHTTP_FLAG_SECURE;
    }
   return WinHttpOpenRequest(hConnect, verb, objectName, NULL, NULL, NULL, flags);
#else
   if (scheme == INTERNET_SCHEME_HTTPS) {
       flags |= INTERNET_FLAG_SECURE;
    }
    return HttpOpenRequest(hConnect, verb, objectName, NULL, NULL, NULL, flags, 0);
#endif
}
BOOL AddRequestHeaders(HINTERNET hRequest, LPCWSTR header)
{
    SIZE_T len = lstrlenW(header);
#ifdef USE_WINHTTP
    return WinHttpAddRequestHeaders(hRequest, header, DWORD(len), WINHTTP_ADDREQ_FLAG_ADD);
#else
    return HttpAddRequestHeaders(hRequest, header, DWORD(len), HTTP_ADDREQ_FLAG_ADD);
#endif
}
BOOL SendRequest(HINTERNET hRequest, const void* body, DWORD size)
{
#ifdef USE_WINHTTP
    return WinHttpSendRequest(hRequest, 0, 0, const_cast<void*>(body), size, size, 0);
#else
   return HttpSendRequest(hRequest, 0, 0, const_cast<void*>(body), size);
#endif
}
BOOL EndRequest(HINTERNET hRequest)
{
#ifdef USE_WINHTTP
    return WinHttpReceiveResponse(hRequest, 0);
#else
   // if you use HttpSendRequestEx to send request then use HttpEndRequest in here!
   return TRUE;
#endif
}
BOOL QueryInfo(HINTERNET hRequest, int queryId, char* szBuf, DWORD* pdwSize)
{
#ifdef USE_WINHTTP
  return WinHttpQueryHeaders(hRequest, (DWORD) queryId, 0, szBuf, pdwSize, 0);
#else
    return HttpQueryInfo(hRequest, queryId, szBuf, pdwSize, 0);
#endif
}
BOOL ReadData(HINTERNET hRequest, void* buffer, DWORD length, DWORD* cbRead)
{
#ifdef USE_WINHTTP
   return WinHttpReadData(hRequest, buffer, length, cbRead);
#else
    return InternetReadFile(hRequest, buffer, length, cbRead);
#endif
}
void CloseInternetHandle(HINTERNET hInternet)
{
  if (hInternet)
    {
#ifdef USE_WINHTTP
       WinHttpCloseHandle(hInternet);
#else
        InternetCloseHandle(hInternet);
#endif
   }
}

  int _tmain(int argc, _TCHAR* argv[])
{
   HINTERNET hSession = 0;
    HINTERNET hConnect = 0;
    HINTERNET hRequest = 0;
    CStringW strHeader(L"Content-type: application/x-www-form-urlencoded/r/n");

    // Test data
    CrackedUrl crackedUrl(L"http://www.easy-creator.net/test2/add.asp");
    CStringA strPostData("value1=10&value2=14");

    // Open session.
    hSession = OpenSession(L"HttpPost by [email protected]");
    if (hSession == NULL) {
        printf("Error:Open session!/n");
        return -1;
    }
    // Connect.
    hConnect = Connect(hSession, crackedUrl.GetHostName(), crackedUrl.GetPort());
    if (hConnect == NULL) {
        printf("Error:Connect failed!/n");
        return -1;
    }
    // Open request.
    hRequest = OpenRequest(hConnect, L"POST", crackedUrl.GetPath(), crackedUrl.GetScheme());
   if (hRequest == NULL) {
        printf("Error:OpenRequest failed!/n");
        return -1;
    }
    // Add request header.
    if (!AddRequestHeaders(hRequest, strHeader)) {
       printf("Error:AddRequestHeaders failed!/n");
        return -1;
   }

    // Send post data.
    if (!SendRequest(hRequest, (const char*)strPostData, strPostData.GetLength())) {
        printf("Error:SendRequest failed!/n");
        return -1;
    }

    // End request
   if (!EndRequest(hRequest)) {
       printf("Error:EndRequest failed!/n");
        return -1;
    }

    char szBuf[BUF_SIZE];
    DWORD dwSize = 0;
    szBuf[0] = 0;
    // Query header info.
#ifdef USE_WINHTTP
    int contextLengthId = WINHTTP_QUERY_CONTENT_LENGTH;
    int statusCodeId = WINHTTP_QUERY_STATUS_CODE;
    int statusTextId = WINHTTP_QUERY_STATUS_TEXT;
#else
    int contextLengthId = HTTP_QUERY_CONTENT_LENGTH;
    int statusCodeId = HTTP_QUERY_STATUS_CODE;
    int statusTextId = HTTP_QUERY_STATUS_TEXT;
#endif
    dwSize = BUF_SIZE;
   if (QueryInfo(hRequest, contextLengthId, szBuf, &dwSize)) {
       szBuf[dwSize] = 0;
        printf("Content length:[%s]/n", szBuf);
    }

    dwSize = BUF_SIZE;
    if (QueryInfo(hRequest, statusCodeId, szBuf, &dwSize)) {
        szBuf[dwSize] = 0;
        printf("Status code:[%s]/n", szBuf);
    }

   dwSize = BUF_SIZE;
   if (QueryInfo(hRequest, statusTextId, szBuf, &dwSize)) {
       szBuf[dwSize] = 0;
        printf("Status text:[%s]/n", szBuf);
    }
    // read data.
   for (;;) {
        dwSize = BUF_SIZE;
        if (ReadData(hRequest, szBuf, dwSize, &dwSize) == FALSE) {
            break;
       }
        if (dwSize <= 0) {
            break;
        }

       szBuf[dwSize] = 0;
        printf("%s/n", szBuf);    //Output value = value1 + value2
    }
    CloseInternetHandle(hRequest);
    CloseInternetHandle(hConnect);
    CloseInternetHandle(hSession);
    return 0;

}

你可能感兴趣的:(使用WinINet和WinHTTP实现Http访问)