使用WinINet和WinHTTP实现Http访问
程序员文章站
2024-02-01 10:14:04
...
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的函数见下:
完整代码如下:
为实现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; }
完整代码如下:
#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 PostToSite(const LPCWSTR url, const char *form_data, char* &szBuf) { 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(url); CStringA strPostData(form_data); // Open session. hSession = OpenSession(L"HttpPost by alien"); 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; } 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); } dwSize = BUF_SIZE; ZeroMemory(szBuf, dwSize); if (ReadData(hRequest, szBuf, dwSize, &dwSize)) { szBuf[dwSize] = 0; } // 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; } DWORD WINAPI ServerThread(LPVOID data){ int nRet = 0; WSADATA wsaData; if( (nRet = WSAStartup(0x202, &wsaData)) != 0 ) { printf("WSAStartup() failed: %d\n",nRet); return 0; } SOCKET saccept; SOCKET slisten=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(slisten == INVALID_SOCKET){ printf("socket failed:%d\n",WSAGetLastError()); return 0; } struct sockaddr_in serv, client; serv.sin_family = AF_INET; serv.sin_port = htons(20000); serv.sin_addr.s_addr = inet_addr("127.0.0.1"); if(bind(slisten, (LPSOCKADDR)&serv, sizeof(serv))){ printf("bind() failed!"); return 0; } if(listen(slisten, 5) == SOCKET_ERROR){ printf("listen failed!"); return 0; } int len = sizeof(client), size; char buf[1024]; while(1){ saccept = accept(slisten, (struct sockaddr*)&client, &len); printf("accept client IP:%s port:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); ZeroMemory(buf, 1024); if((size = recv(saccept, buf, 1024, 0))){ printf("buf: %s %d\n", buf, size); } closesocket(saccept); } closesocket(slisten); WSACleanup(); } int _tmain(int argc, _TCHAR* argv[]) { HANDLE serverThread; char *buffer = new char[BUF_SIZE]; serverThread = CreateThread(NULL, 0, ServerThread, NULL, 0, 0); PostToSite(L"http://localhost/chess/login.php","name=alien&pwd=alienchang", buffer); printf("%s\n", buffer); PostToSite(L"http://localhost/chess/chooseRoom.php","uid=1&sid=4", buffer); printf("%s\n", buffer); WaitForSingleObject(serverThread, 1000); return 0; }
上一篇: 包装类和基本类型的转换
下一篇: 包装类和基本类型的转换
推荐阅读
-
使用WinINet和WinHTTP实现Http访问
-
HTTP实验:分别使用httpd-2.2和httpd-2.4实现
-
Linux下SVN服务器同时支持Apache的http和svnserve独立服务器两种模式且使用相同的访问权限账号
-
tomcat同时使用http和https访问的配置方法
-
使用nginx实现http访问自动跳转到https端口
-
使用前置通知进行访问控制:通过方法参数决定是否可以访问该方法,分别使用基于XML的声明式AspectJ和基于注解的声明式AspectJ来实现。
-
HTTP实验:分别使用httpd-2.2和httpd-2.4实现
-
使用nginx实现http访问自动跳转到https端口
-
Linux下SVN服务器同时支持Apache的http和svnserve独立服务器两种模式且使用相同的访问权限账号
-
php 实现使用curl模拟ip和来源进行访问的方法