1、C+调用HTTP实现方式C+调用HTTP实现方式2011-09-24 17:00:52|分类:C+|字号订阅Http访问有两种方式,GET和POST,就编程来说GET方式相对简单点,它不用向服务器提交数据,程序中使用POST方式,提交数据并从服务器获取返回值。为实现Http访问,微软提供了二套API:WinINet, WinHTTP。WinHTTP比WinINet更加安全和健壮,可以这么认为WinHTTP是WinINet的升级版本。程序中,通过一个宏的设置来决定是使用WinHttp还是WinINet。#define USE_WINHTTP /Comment this line to user
2、wininet.下面来说说实现Http访问的流程(两套API都一样的流程):1, 首先我们打开一个Session获得一个HINTERNET session句柄;2, 然后我们使用这个session句柄与服务器连接得到一个HINTERNET connect句柄;3, 然后我们使用这个connect句柄来打开Http 请求得到一个HINTERNET request句柄;4, 这时我们就可以使用这个request句柄来发送数据与读取从服务器返回的数据;5, 最后依次关闭request,connect,session句柄。/*定义HTTP发送所用方法*/HINTERNET OpenSession(LP
3、CWSTR userAgent = 0)#ifdef USE_WINHTTP return WinHttpOpen(userAgent, NULL, NULL, NULL, NULL);#else return InternetOpen(userAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);#endifHINTERNET Connect(HINTERNET hSession, LPCWSTR serverAddr, int portNo)#ifdef USE_WINHTTP return WinHttpConnect(hSession,
4、 serverAddr, (INTERNET_PORT) portNo, 0);#else return InternetConnect(hSession, serverAddr, portNo, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);#endifHINTERNET OpenRequest(HINTERNET hConnect, LPCWSTR verb, LPCWSTR objectName, int scheme) DWORD flags = 0;#ifdef USE_WINHTTP if (scheme = INTERNET_SCHEME_HT
5、TPS) 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);#endifBOOL AddRequestHeaders(HINTE
6、RNET 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);#endifBOOL SendRequest(HINTERNET hRequest, con
7、st void* body, DWORD size)#ifdef USE_WINHTTP return WinHttpSendRequest(hRequest, 0, 0, const_cast(body), size, size, 0);#else return HttpSendRequest(hRequest, 0, 0, const_cast(body), size);#endifBOOL EndRequest(HINTERNET hRequest)#ifdef USE_WINHTTP return WinHttpReceiveResponse(hRequest, 0);#else /
8、if you use HttpSendRequestEx to send request then use HttpEndRequest in here! return TRUE;#endifBOOL QueryInfo(HINTERNET hRequest, int queryId, char* szBuf, DWORD* pdwSize)#ifdef USE_WINHTTP return WinHttpQueryHeaders(hRequest, (DWORD) queryId, 0, szBuf, pdwSize, 0);#else return HttpQueryInfo(hReque
9、st, queryId, szBuf, pdwSize, 0);#endifBOOL 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);#endifvoid CloseInternetHandle(HINTERNET hInte
10、rnet) if (hInternet)#ifdef USE_WINHTTP WinHttpCloseHandle(hInternet);#else InternetCloseHandle(hInternet);#endif /*/通过Http方式发送短信string SendSMS_HTTP(const long ececcid,const string & password ,const string & msisdn, const string &smsContent)string rtnStr =-1; HINTERNET hSession = 0; HINTERNET hConnec
11、t = 0; HINTERNET hRequest = 0; wstring strHeader(LContent-type: application/x-www-form-urlencodedrn); / Test data CrackedUrl crackedUrl(Lstring StrPostData = ececcid=600000&password=+password+&msisdn=+msisdn+&smscontent=+smsContent+&msgtype=5&longcode=;StrPostData = string_To_UTF8(StrPostData); / Op
12、en session. hSession = OpenSession(LHttpPost bylyz_sea); if (hSession = NULL) coutError:Open session!n; return -1; / Connect. hConnect = Connect(hSession, crackedUrl.GetHostName(), crackedUrl.GetPort(); if (hConnect = NULL) coutError:Connect failed!n; return -1; / Open request. hRequest = OpenReques
13、t(hConnect, LPOST, crackedUrl.GetPath(), crackedUrl.GetScheme(); if (hRequest = NULL) coutError:OpenRequest failed!n; return -1; / Add request header.if (!AddRequestHeaders(hRequest, strHeader.c_str() coutError:AddRequestHeaders failed!n; return -1; / Send post data.if (!SendRequest(hRequest, StrPos
14、tData.c_str(), StrPostData.length() coutError:SendRequest failed!n; return -1; / End request if (!EndRequest(hRequest) coutError:EndRequest failed!n; return -1; char szBufBUF_SIZE; DWORD dwSize = 0; szBuf0 = 0; / Query header info.#ifdef USE_WINHTTP int contextLengthId = WINHTTP_QUERY_CONTENT_LENGTH
15、; 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,
16、szBuf, &dwSize) szBufdwSize = 0; coutContent length: szBufendl; dwSize = BUF_SIZE; if (QueryInfo(hRequest, statusCodeId, szBuf, &dwSize) szBufdwSize = 0; coutStatus code: szBufendl; dwSize = BUF_SIZE; if (QueryInfo(hRequest, statusTextId, szBuf, &dwSize) szBufdwSize = 0; coutStatus text:szBufendl; /
17、 read data. for (;) dwSize = BUF_SIZE; if (ReadData(hRequest, szBuf, dwSize, &dwSize) = FALSE) break; if (dwSize = 0) break; szBufdwSize = 0;rtnStr =:UTF8_To_string(string(szBuf);coutrtnStrendl;/Output 返回值 CloseInternetHandle(hRequest); CloseInternetHandle(hConnect); CloseInternetHandle(hSession);re
18、turn rtnStr;以上方法中用到的CrackURL方法在以下CrackURL.h文件中:#pragma once/#include/using namespace std;#define USE_WINHTTP /Comment this line to user wininet.#ifdef USE_WINHTTP #include #pragma comment(lib, winhttp.lib)#else #include #pragma comment(lib, wininet.lib)#endif/ CrackedUrlclass CrackedUrl int m_scheme
19、; wstring m_host; int m_port; wstring m_path;public: CrackedUrl(LPCWSTR url) URL_COMPONENTS uc = 0; uc.dwStructSize = sizeof(uc); const DWORD BUF_LEN = 256; WCHAR hostBUF_LEN; uc.lpszHostName = host; uc.dwHostNameLength = BUF_LEN; WCHAR pathBUF_LEN; uc.lpszUrlPath = path; uc.dwUrlPathLength = BUF_LE
20、N; WCHAR extraBUF_LEN; uc.lpszExtraInfo = extra; uc.dwExtraInfoLength = BUF_LEN;#ifdef USE_WINHTTP if (!WinHttpCrackUrl(url, 0, ICU_ESCAPE, &uc) coutError:WinHttpCrackUrl failed!n; #else if (!InternetCrackUrl(url, 0, ICU_ESCAPE, &uc) printf(Error:InternetCrackUrl failed!n); #endif m_scheme = uc.nSch
21、eme; m_host = host; m_port = uc.nPort; m_path = path; int GetScheme() const return m_scheme; LPCWSTR GetHostName() const return m_host.c_str(); int GetPort() const return m_port; LPCWSTR GetPath() const return m_path.c_str(); static string UrlEncode(const char* p) if (p = 0) return string(); string 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 c16; wsprintfA(c, %02X, ch); buf += c; return buf; ;