码迷,mamicode.com
首页 > Windows程序 > 详细

使用WinINet和WinHTTP实现Http訪问

时间:2014-10-22 12:34:08      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   使用   for   

使用WinINetWinHTTP实现Http訪问

飘飘白云 l_zhaohui@163.com 2007-11-30

 

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

为实现Http訪问,微软提供了二APIWinINet, WinHTTPWinHTTPWinINet更加安全和健壮能够这么觉得WinHTTPWinINet的升级版本号这两套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句柄与server连接得到一个HINTERNET connect句柄;

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

4, 这时我们就能够使用这个request句柄来发送数据与读取从server返回的数据;

5, 最后依次关闭requestconnectsession句柄。

 

在这个例程中以上各个流程都进行了简单封装,以便对照两套API函数的些许差异。以下让源码说话,原project是一个windows控制台project,你能够非常easy通过拷贝代码重建project。

 

另:假设你从server得到的返回数据是utf8格式的文本数据,你将须要对返回的数据进行转换才干正确显示中文,日文等。仅供參考,转换为ATL CStringW的函数见下:

 

bubuko.com,布布扣CStringW GetStringWFromUtf8(const std::string& str)
bubuko.com,布布扣
{
bubuko.com,布布扣    
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), int(str.length()), 00);
bubuko.com,布布扣
bubuko.com,布布扣    CStringW buf;
bubuko.com,布布扣    WCHAR
*    dd = buf.GetBuffer(len);
bubuko.com,布布扣
bubuko.com,布布扣    len 
= MultiByteToWideChar(CP_UTF8, 0, str.c_str(), int(str.length()), dd, len);
bubuko.com,布布扣
bubuko.com,布布扣    buf.ReleaseBuffer(len);
bubuko.com,布布扣
bubuko.com,布布扣    
return buf;
bubuko.com,布布扣}

完整代码例如以下:
  1bubuko.com,布布扣// HttpPost.cpp written by l_zhaohui@163.com
  2bubuko.com,布布扣// 2007/11/30
  3bubuko.com,布布扣#include "stdafx.h"
  4bubuko.com,布布扣#include <windows.h>
  5bubuko.com,布布扣#include <stdio.h>
  6bubuko.com,布布扣#include <stdlib.h>
  7bubuko.com,布布扣
  8bubuko.com,布布扣#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
  9bubuko.com,布布扣#include <atlbase.h>
 10bubuko.com,布布扣#include <atlstr.h>
 11bubuko.com,布布扣
 12bubuko.com,布布扣#define USE_WINHTTP    //Comment this line to user wininet.
 13bubuko.com,布布扣#ifdef USE_WINHTTP
 14bubuko.com,布布扣    #include <winhttp.h>
 15bubuko.com,布布扣    #pragma comment(lib, "winhttp.lib")
 16bubuko.com,布布扣#else
 17bubuko.com,布布扣    #include <wininet.h>
 18bubuko.com,布布扣    #pragma comment(lib, "wininet.lib")
 19bubuko.com,布布扣#endif
 20bubuko.com,布布扣#define BUF_SIZE    (1024)
 21bubuko.com,布布扣
 22bubuko.com,布布扣// CrackedUrl
 23bubuko.com,布布扣class CrackedUrl {
 24bubuko.com,布布扣    int m_scheme;
 25bubuko.com,布布扣    CStringW m_host;
 26bubuko.com,布布扣    int m_port;
 27bubuko.com,布布扣    CStringW m_path;
 28bubuko.com,布布扣public:
 29bubuko.com,布布扣    CrackedUrl(LPCWSTR url)
 30bubuko.com,布布扣    {
 31bubuko.com,布布扣        URL_COMPONENTS uc = 0};
 32bubuko.com,布布扣        uc.dwStructSize = sizeof(uc);
 33bubuko.com,布布扣
 34bubuko.com,布布扣        const DWORD BUF_LEN = 256;
 35bubuko.com,布布扣
 36bubuko.com,布布扣        WCHAR host[BUF_LEN];
 37bubuko.com,布布扣        uc.lpszHostName = host;
 38bubuko.com,布布扣        uc.dwHostNameLength = BUF_LEN;
 39bubuko.com,布布扣
 40bubuko.com,布布扣        WCHAR path[BUF_LEN];
 41bubuko.com,布布扣        uc.lpszUrlPath = path;
 42bubuko.com,布布扣        uc.dwUrlPathLength = BUF_LEN;
 43bubuko.com,布布扣
 44bubuko.com,布布扣        WCHAR extra[BUF_LEN];
 45bubuko.com,布布扣        uc.lpszExtraInfo = extra;
 46bubuko.com,布布扣        uc.dwExtraInfoLength = BUF_LEN;
 47bubuko.com,布布扣
 48bubuko.com,布布扣#ifdef USE_WINHTTP
 49bubuko.com,布布扣        if (!WinHttpCrackUrl(url, 0, ICU_ESCAPE, &uc)) {
 50bubuko.com,布布扣            printf("Error:WinHttpCrackUrl failed!/n");
 51bubuko.com,布布扣        }

 52bubuko.com,布布扣
 53bubuko.com,布布扣#else
 54bubuko.com,布布扣        if (!InternetCrackUrl(url, 0, ICU_ESCAPE, &uc)) {
 55bubuko.com,布布扣            printf("Error:InternetCrackUrl failed!/n");
 56bubuko.com,布布扣        }

 57bubuko.com,布布扣#endif
 58bubuko.com,布布扣        m_scheme = uc.nScheme;
 59bubuko.com,布布扣        m_host = host;
 60bubuko.com,布布扣        m_port = uc.nPort;
 61bubuko.com,布布扣        m_path = path;
 62bubuko.com,布布扣    }

 63bubuko.com,布布扣
 64bubuko.com,布布扣    int GetScheme() const
 65bubuko.com,布布扣    {
 66bubuko.com,布布扣        return m_scheme;
 67bubuko.com,布布扣    }

 68bubuko.com,布布扣
 69bubuko.com,布布扣    LPCWSTR GetHostName() const
 70bubuko.com,布布扣    {
 71bubuko.com,布布扣        return m_host;
 72bubuko.com,布布扣    }

 73bubuko.com,布布扣
 74bubuko.com,布布扣    int GetPort() const
 75bubuko.com,布布扣    {
 76bubuko.com,布布扣        return m_port;
 77bubuko.com,布布扣    }

 78bubuko.com,布布扣
 79bubuko.com,布布扣    LPCWSTR GetPath() const
 80bubuko.com,布布扣    {
 81bubuko.com,布布扣        return m_path;
 82bubuko.com,布布扣    }

 83bubuko.com,布布扣
 84bubuko.com,布布扣    static CStringA UrlEncode(const char* p)
 85bubuko.com,布布扣    {
 86bubuko.com,布布扣        if (p == 0{
 87bubuko.com,布布扣            return CStringA();
 88bubuko.com,布布扣        }

 89bubuko.com,布布扣
 90bubuko.com,布布扣        CStringA buf;
 91bubuko.com,布布扣
 92bubuko.com,布布扣        for (;;) {
 93bubuko.com,布布扣            int ch = (BYTE) (*(p++));
 94bubuko.com,布布扣            if (ch == /0{
 95bubuko.com,布布扣                break;
 96bubuko.com,布布扣            }

 97bubuko.com,布布扣
 98bubuko.com,布布扣            if (isalnum(ch) || ch == _ || ch == - || ch == .{
 99bubuko.com,布布扣                buf += (char)ch;
100bubuko.com,布布扣            }

101bubuko.com,布布扣            else if (ch ==  {
102bubuko.com,布布扣                buf += +;
103bubuko.com,布布扣            }

104bubuko.com,布布扣            else {
105bubuko.com,布布扣                char c[16];
106bubuko.com,布布扣                wsprintfA(c, "%%%02X", ch);
107bubuko.com,布布扣                buf += c;
108bubuko.com,布布扣            }

109bubuko.com,布布扣        }

110bubuko.com,布布扣
111bubuko.com,布布扣        return buf;
112bubuko.com,布布扣    }

113bubuko.com,布布扣}
;
114bubuko.com,布布扣
115bubuko.com,布布扣// CrackedUrl
116bubuko.com,布布扣HINTERNET OpenSession(LPCWSTR userAgent = 0)
117bubuko.com,布布扣{
118bubuko.com,布布扣#ifdef USE_WINHTTP
119bubuko.com,布布扣    return WinHttpOpen(userAgent, NULL, NULL, NULL, NULL);;
120bubuko.com,布布扣#else
121bubuko.com,布布扣    return InternetOpen(userAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
122bubuko.com,布布扣#endif
123bubuko.com,布布扣}

124bubuko.com,布布扣
125bubuko.com,布布扣HINTERNET Connect(HINTERNET hSession, LPCWSTR serverAddr, int portNo)
126bubuko.com,布布扣{
127bubuko.com,布布扣#ifdef USE_WINHTTP
128bubuko.com,布布扣    return WinHttpConnect(hSession, serverAddr, (INTERNET_PORT) portNo, 0);
129bubuko.com,布布扣#else
130bubuko.com,布布扣    return InternetConnect(hSession, serverAddr, portNo, NULL, NULL, INTERNET_SERVICE_HTTP, 00);
131bubuko.com,布布扣#endif
132bubuko.com,布布扣}

133bubuko.com,布布扣
134bubuko.com,布布扣HINTERNET OpenRequest(HINTERNET hConnect, LPCWSTR verb, LPCWSTR objectName, int scheme)
135bubuko.com,布布扣{
136bubuko.com,布布扣    DWORD flags = 0;
137bubuko.com,布布扣#ifdef USE_WINHTTP
138bubuko.com,布布扣    if (scheme == INTERNET_SCHEME_HTTPS) {
139bubuko.com,布布扣        flags |= WINHTTP_FLAG_SECURE;
140bubuko.com,布布扣    }

141bubuko.com,布布扣
142bubuko.com,布布扣    return WinHttpOpenRequest(hConnect, verb, objectName, NULL, NULL, NULL, flags);
143bubuko.com,布布扣
144bubuko.com,布布扣#else
145bubuko.com,布布扣    if (scheme == INTERNET_SCHEME_HTTPS) {
146bubuko.com,布布扣        flags |= INTERNET_FLAG_SECURE;
147bubuko.com,布布扣    }

148bubuko.com,布布扣
149bubuko.com,布布扣    return HttpOpenRequest(hConnect, verb, objectName, NULL, NULL, NULL, flags, 0);
150bubuko.com,布布扣#endif
151bubuko.com,布布扣}

152bubuko.com,布布扣
153bubuko.com,布布扣BOOL AddRequestHeaders(HINTERNET hRequest, LPCWSTR header)
154bubuko.com,布布扣{
155bubuko.com,布布扣    SIZE_T len = lstrlenW(header);
156bubuko.com,布布扣#ifdef USE_WINHTTP
157bubuko.com,布布扣    return WinHttpAddRequestHeaders(hRequest, header, DWORD(len), WINHTTP_ADDREQ_FLAG_ADD);
158bubuko.com,布布扣#else
159bubuko.com,布布扣    return HttpAddRequestHeaders(hRequest, header, DWORD(len), HTTP_ADDREQ_FLAG_ADD);
160bubuko.com,布布扣#endif
161bubuko.com,布布扣}

162bubuko.com,布布扣
163bubuko.com,布布扣BOOL SendRequest(HINTERNET hRequest, const void* body, DWORD size)
164bubuko.com,布布扣{
165bubuko.com,布布扣#ifdef USE_WINHTTP
166bubuko.com,布布扣    return WinHttpSendRequest(hRequest, 00, const_cast<void*>(body), size, size, 0);
167bubuko.com,布布扣#else
168bubuko.com,布布扣    return HttpSendRequest(hRequest, 00, const_cast<void*>(body), size);
169bubuko.com,布布扣#endif
170bubuko.com,布布扣}

171bubuko.com,布布扣
172bubuko.com,布布扣BOOL EndRequest(HINTERNET hRequest)
173bubuko.com,布布扣{
174bubuko.com,布布扣#ifdef USE_WINHTTP
175bubuko.com,布布扣    return WinHttpReceiveResponse(hRequest, 0);
176bubuko.com,布布扣#else
177bubuko.com,布布扣    // if you use HttpSendRequestEx to send request then use HttpEndRequest in here!
178bubuko.com,布布扣    return TRUE;
179bubuko.com,布布扣#endif
180bubuko.com,布布扣}

181bubuko.com,布布扣
182bubuko.com,布布扣BOOL QueryInfo(HINTERNET hRequest, int queryId, char* szBuf, DWORD* pdwSize)
183bubuko.com,布布扣{
184bubuko.com,布布扣#ifdef USE_WINHTTP
185bubuko.com,布布扣    return WinHttpQueryHeaders(hRequest, (DWORD) queryId, 0, szBuf, pdwSize, 0);
186bubuko.com,布布扣#else
187bubuko.com,布布扣    return HttpQueryInfo(hRequest, queryId, szBuf, pdwSize, 0);
188bubuko.com,布布扣#endif
189bubuko.com,布布扣}

190bubuko.com,布布扣
191bubuko.com,布布扣BOOL ReadData(HINTERNET hRequest, void* buffer, DWORD length, DWORD* cbRead)
192bubuko.com,布布扣{
193bubuko.com,布布扣#ifdef USE_WINHTTP
194bubuko.com,布布扣    return WinHttpReadData(hRequest, buffer, length, cbRead);
195bubuko.com,布布扣#else
196bubuko.com,布布扣    return InternetReadFile(hRequest, buffer, length, cbRead);
197bubuko.com,布布扣#endif
198bubuko.com,布布扣}

199bubuko.com,布布扣
200bubuko.com,布布扣void CloseInternetHandle(HINTERNET hInternet)
201bubuko.com,布布扣{
202bubuko.com,布布扣    if (hInternet)
203bubuko.com,布布扣    {
204bubuko.com,布布扣#ifdef USE_WINHTTP
205bubuko.com,布布扣        WinHttpCloseHandle(hInternet);
206bubuko.com,布布扣#else
207bubuko.com,布布扣        InternetCloseHandle(hInternet);
208bubuko.com,布布扣#endif
209bubuko.com,布布扣    }

210bubuko.com,布布扣}

211bubuko.com,布布扣
212bubuko.com,布布扣int _tmain(int argc, _TCHAR* argv[])
213bubuko.com,布布扣{
214bubuko.com,布布扣    HINTERNET hSession = 0;
215bubuko.com,布布扣    HINTERNET hConnect = 0;
216bubuko.com,布布扣    HINTERNET hRequest = 0;
217bubuko.com,布布扣    CStringW strHeader(L"Content-type: application/x-www-form-urlencoded/r/n");
218bubuko.com,布布扣
219bubuko.com,布布扣    // Test data
220bubuko.com,布布扣    CrackedUrl crackedUrl(L"http://www.easy-creator.net/test2/add.asp");
221bubuko.com,布布扣    CStringA strPostData("value1=10&value2=14");
222bubuko.com,布布扣
223bubuko.com,布布扣    // Open session.
224bubuko.com,布布扣    hSession = OpenSession(L"HttpPost by l_zhaohui@163.com");
225bubuko.com,布布扣    if (hSession == NULL) {
226bubuko.com,布布扣        printf("Error:Open session!/n");
227bubuko.com,布布扣        return -1;
228bubuko.com,布布扣    }

229bubuko.com,布布扣
230bubuko.com,布布扣    // Connect.
231bubuko.com,布布扣    hConnect = Connect(hSession, crackedUrl.GetHostName(), crackedUrl.GetPort());
232bubuko.com,布布扣    if (hConnect == NULL) {
233bubuko.com,布布扣        printf("Error:Connect failed!/n");
234bubuko.com,布布扣        return -1;
235bubuko.com,布布扣    }

236bubuko.com,布布扣
237bubuko.com,布布扣    // Open request.
238bubuko.com,布布扣    hRequest = OpenRequest(hConnect, L"POST", crackedUrl.GetPath(), crackedUrl.GetScheme());
239bubuko.com,布布扣    if (hRequest == NULL) {
240bubuko.com,布布扣        printf("Error:OpenRequest failed!/n");
241bubuko.com,布布扣        return -1;
242bubuko.com,布布扣    }

243bubuko.com,布布扣
244bubuko.com,布布扣    // Add request header.
245bubuko.com,布布扣    if (!AddRequestHeaders(hRequest, strHeader)) {
246bubuko.com,布布扣        printf("Error:AddRequestHeaders failed!/n");
247bubuko.com,布布扣        return -1;
248bubuko.com,布布扣    }

249bubuko.com,布布扣
250bubuko.com,布布扣    // Send post data.
251bubuko.com,布布扣    if (!SendRequest(hRequest, (const char*)strPostData, strPostData.GetLength())) {
252bubuko.com,布布扣        printf("Error:SendRequest failed!/n");
253bubuko.com,布布扣        return -1;
254bubuko.com,布布扣    }

255bubuko.com,布布扣
256bubuko.com,布布扣    // End request
257bubuko.com,布布扣    if (!EndRequest(hRequest)) {
258bubuko.com,布布扣        printf("Error:EndRequest failed!/n");
259bubuko.com,布布扣        return -1;
260bubuko.com,布布扣    }

261bubuko.com,布布扣
262bubuko.com,布布扣    char szBuf[BUF_SIZE];
263bubuko.com,布布扣    DWORD dwSize = 0;
264bubuko.com,布布扣    szBuf[0= 0;
265bubuko.com,布布扣
266bubuko.com,布布扣    // Query header info.
267bubuko.com,布布扣#ifdef USE_WINHTTP
268bubuko.com,布布扣    int contextLengthId = WINHTTP_QUERY_CONTENT_LENGTH;
269bubuko.com,布布扣    int statusCodeId = WINHTTP_QUERY_STATUS_CODE;
270bubuko.com,布布扣    int statusTextId = WINHTTP_QUERY_STATUS_TEXT;
271bubuko.com,布布扣#else
272bubuko.com,布布扣    int contextLengthId = HTTP_QUERY_CONTENT_LENGTH;
273bubuko.com,布布扣    int statusCodeId = HTTP_QUERY_STATUS_CODE;
274bubuko.com,布布扣    int statusTextId = HTTP_QUERY_STATUS_TEXT;
275bubuko.com,布布扣#endif
276bubuko.com,布布扣    dwSize = BUF_SIZE;
277bubuko.com,布布扣    if (QueryInfo(hRequest, contextLengthId, szBuf, &dwSize)) {
278bubuko.com,布布扣        szBuf[dwSize] = 0;
279bubuko.com,布布扣        printf("Content length:[%s]/n", szBuf);
280bubuko.com,布布扣    }

281bubuko.com,布布扣
282bubuko.com,布布扣    dwSize = BUF_SIZE;
283bubuko.com,布布扣    if (QueryInfo(hRequest, statusCodeId, szBuf, &dwSize)) {
284bubuko.com,布布扣        szBuf[dwSize] = 0;
285bubuko.com,布布扣        printf("Status code:[%s]/n", szBuf);
286bubuko.com,布布扣    }

287bubuko.com,布布扣
288bubuko.com,布布扣    dwSize = BUF_SIZE;
289bubuko.com,布布扣    if (QueryInfo(hRequest, statusTextId, szBuf, &dwSize)) {
290bubuko.com,布布扣        szBuf[dwSize] = 0;
291bubuko.com,布布扣        printf("Status text:[%s]/n", szBuf);
292bubuko.com,布布扣    }

293bubuko.com,布布扣
294bubuko.com,布布扣    // read data.
295bubuko.com,布布扣    for (;;) {
296bubuko.com,布布扣        dwSize = BUF_SIZE;
297bubuko.com,布布扣        if (ReadData(hRequest, szBuf, dwSize, &dwSize) == FALSE) {
298bubuko.com,布布扣            break;
299bubuko.com,布布扣        }

300bubuko.com,布布扣
301bubuko.com,布布扣        if (dwSize <= 0{
302bubuko.com,布布扣            break;
303bubuko.com,布布扣        }

304bubuko.com,布布扣
305bubuko.com,布布扣        szBuf[dwSize] = 0;
306bubuko.com,布布扣        printf("%s/n", szBuf);    //Output value = value1 + value2
307bubuko.com,布布扣    }

308bubuko.com,布布扣
309bubuko.com,布布扣    CloseInternetHandle(hRequest);
310bubuko.com,布布扣    CloseInternetHandle(hConnect);
311bubuko.com,布布扣    CloseInternetHandle(hSession);
312bubuko.com,布布扣
313bubuko.com,布布扣    return 0;
314bubuko.com,布布扣}

315bubuko.com,布布扣

使用WinINet和WinHTTP实现Http訪问

标签:style   blog   http   color   io   os   ar   使用   for   

原文地址:http://www.cnblogs.com/yxwkf/p/4042697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!