使用WinINet和WinHTTP实现Http访问
2013-01-11 13:42
357 查看
Http访问有两种方式,GET和POST,就编程来说GET方式相对简单点,它不用向服务器提交数据,在这个例程中我使用POST方式,提交数据value1与value2,并从服务器得到他们的和(value1
+value2)。
为实现Http访问,微软提供了二套API:WinINet,WinHTTP。WinHTTP比WinINet更加安全和健壮,可以这么认为WinHTTP是WinINet的升级版本。这两套API包含了很多相似的函数与宏定义,呵呵,详细对比请查阅msdn中的文章“Porting
WinINetApplicationstoWinHTTP”,在线MSDN连接:http://msdn2.microsoft.com/en-us/library/aa384068.aspx。在这个例程中,通过一个宏的设置来决定是使用WinHttp还是WinINet。代码如下:
#defineUSE_WINHTTP//Commentthislinetouserwininet.
下面来说说实现Http访问的流程(两套API都一样的流程):
1,首先我们打开一个Session获得一个HINTERNETsession句柄;
2,然后我们使用这个session句柄与服务器连接得到一个HINTERNETconnect句柄;
3,然后我们使用这个connect句柄来打开Http
请求得到一个HINTERNETrequest句柄;
4,这时我们就可以使用这个request句柄来发送数据与读取从服务器返回的数据;
5,最后依次关闭request,connect,session句柄。
在这个例程中以上各个流程都进行了简单封装,以便对比两套API函数的些许差异。下面让源代码说话,原工程是一个windows控制台工程,你可以很容易通过拷贝代码重建工程。
另:如果你从服务器得到的返回数据是utf8格式的文本数据,你将需要对返回的数据进行转换才能正确显示中文,日文等。仅供参考,转换为ATLCStringW的函数见下:
完整代码如下:
+value2)。
为实现Http访问,微软提供了二套API:WinINet,WinHTTP。WinHTTP比WinINet更加安全和健壮,可以这么认为WinHTTP是WinINet的升级版本。这两套API包含了很多相似的函数与宏定义,呵呵,详细对比请查阅msdn中的文章“Porting
WinINetApplicationstoWinHTTP”,在线MSDN连接:
#defineUSE_WINHTTP//Commentthislinetouserwininet.
下面来说说实现Http访问的流程(两套API都一样的流程):
1,首先我们打开一个Session获得一个HINTERNETsession句柄;
2,然后我们使用这个session句柄与服务器连接得到一个HINTERNETconnect句柄;
3,然后我们使用这个connect句柄来打开Http
请求得到一个HINTERNETrequest句柄;
4,这时我们就可以使用这个request句柄来发送数据与读取从服务器返回的数据;
5,最后依次关闭request,connect,session句柄。
在这个例程中以上各个流程都进行了简单封装,以便对比两套API函数的些许差异。下面让源代码说话,原工程是一个windows控制台工程,你可以很容易通过拷贝代码重建工程。
另:如果你从服务器得到的返回数据是utf8格式的文本数据,你将需要对返回的数据进行转换才能正确显示中文,日文等。仅供参考,转换为ATLCStringW的函数见下:
CStringWGetStringWFromUtf8(conststd::string&str) { intlen=MultiByteToWideChar(CP_UTF8,0,str.c_str(),int(str.length()),0,0); CStringWbuf; WCHAR*dd=buf.GetBuffer(len); len=MultiByteToWideChar(CP_UTF8,0,str.c_str(),int(str.length()),dd,len); buf.ReleaseBuffer(len); returnbuf; }
完整代码如下:
#include"stdafx.h" #include<windows.h> #include<stdio.h> #include<stdlib.h> #define_ATL_CSTRING_EXPLICIT_CONSTRUCTORS #include<atlbase.h> #include<atlstr.h> #defineUSE_WINHTTP//Commentthislinetouserwininet. #ifdefUSE_WINHTTP #include<winhttp.h> #pragmacomment(lib,"winhttp.lib") #else #include<wininet.h> #pragmacomment(lib,"wininet.lib") #endif #defineBUF_SIZE(1024) //CrackedUrl classCrackedUrl{ intm_scheme; CStringWm_host; intm_port; CStringWm_path; public: CrackedUrl(LPCWSTRurl) { URL_COMPONENTSuc={0}; uc.dwStructSize=sizeof(uc); constDWORDBUF_LEN=256; WCHARhost[BUF_LEN]; uc.lpszHostName=host; uc.dwHostNameLength=BUF_LEN; WCHARpath[BUF_LEN]; uc.lpszUrlPath=path; uc.dwUrlPathLength=BUF_LEN; WCHARextra[BUF_LEN]; uc.lpszExtraInfo=extra; uc.dwExtraInfoLength=BUF_LEN; #ifdefUSE_WINHTTP if(!WinHttpCrackUrl(url,0,ICU_ESCAPE,&uc)){ printf("Error:WinHttpCrackUrlfailed!/n"); } #else if(!InternetCrackUrl(url,0,ICU_ESCAPE,&uc)){ printf("Error:InternetCrackUrlfailed!/n"); } #endif m_scheme=uc.nScheme; m_host=host; m_port=uc.nPort; m_path=path; } intGetScheme()const { returnm_scheme; } LPCWSTRGetHostName()const { returnm_host; } intGetPort()const { returnm_port; } LPCWSTRGetPath()const { returnm_path; } staticCStringAUrlEncode(constchar*p) { if(p==0){ returnCStringA(); } CStringAbuf; for(;;){ intch=(BYTE)(*(p++)); if(ch=='/0'){ break; } if(isalnum(ch)||ch=='_'||ch=='-'||ch=='.'){ buf+=(char)ch; } elseif(ch==''){ buf+='+'; } else{ charc[16]; wsprintfA(c,"%%%02X",ch); buf+=c; } } returnbuf; } }; //CrackedUrl HINTERNETOpenSession(LPCWSTRuserAgent=0) { #ifdefUSE_WINHTTP returnWinHttpOpen(userAgent,NULL,NULL,NULL,NULL);; #else returnInternetOpen(userAgent,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); #endif } HINTERNETConnect(HINTERNEThSession,LPCWSTRserverAddr,intportNo) { #ifdefUSE_WINHTTP returnWinHttpConnect(hSession,serverAddr,(INTERNET_PORT)portNo,0); #else returnInternetConnect(hSession,serverAddr,portNo,NULL,NULL,INTERNET_SERVICE_HTTP,0,0); #endif } HINTERNETOpenRequest(HINTERNEThConnect,LPCWSTRverb,LPCWSTRobjectName,intscheme) { DWORDflags=0; #ifdefUSE_WINHTTP if(scheme==INTERNET_SCHEME_HTTPS){ flags|=WINHTTP_FLAG_SECURE; } returnWinHttpOpenRequest(hConnect,verb,objectName,NULL,NULL,NULL,flags); #else if(scheme==INTERNET_SCHEME_HTTPS){ flags|=INTERNET_FLAG_SECURE; } returnHttpOpenRequest(hConnect,verb,objectName,NULL,NULL,NULL,flags,0); #endif } BOOLAddRequestHeaders(HINTERNEThRequest,LPCWSTRheader) { SIZE_Tlen=lstrlenW(header); #ifdefUSE_WINHTTP returnWinHttpAddRequestHeaders(hRequest,header,DWORD(len),WINHTTP_ADDREQ_FLAG_ADD); #else returnHttpAddRequestHeaders(hRequest,header,DWORD(len),HTTP_ADDREQ_FLAG_ADD); #endif } BOOLSendRequest(HINTERNEThRequest,constvoid*body,DWORDsize) { #ifdefUSE_WINHTTP returnWinHttpSendRequest(hRequest,0,0,const_cast<void*>(body),size,size,0); #else returnHttpSendRequest(hRequest,0,0,const_cast<void*>(body),size); #endif } BOOLEndRequest(HINTERNEThRequest) { #ifdefUSE_WINHTTP returnWinHttpReceiveResponse(hRequest,0); #else //ifyouuseHttpSendRequestExtosendrequestthenuseHttpEndRequestinhere! returnTRUE; #endif } BOOLQueryInfo(HINTERNEThRequest,intqueryId,char*szBuf,DWORD*pdwSize) { #ifdefUSE_WINHTTP returnWinHttpQueryHeaders(hRequest,(DWORD)queryId,0,szBuf,pdwSize,0); #else returnHttpQueryInfo(hRequest,queryId,szBuf,pdwSize,0); #endif } BOOLReadData(HINTERNEThRequest,void*buffer,DWORDlength,DWORD*cbRead) { #ifdefUSE_WINHTTP returnWinHttpReadData(hRequest,buffer,length,cbRead); #else returnInternetReadFile(hRequest,buffer,length,cbRead); #endif } voidCloseInternetHandle(HINTERNEThInternet) { if(hInternet) { #ifdefUSE_WINHTTP WinHttpCloseHandle(hInternet); #else InternetCloseHandle(hInternet); #endif } } int_tmain(intargc,_TCHAR*argv[]) { HINTERNEThSession=0; HINTERNEThConnect=0; HINTERNEThRequest=0; CStringWstrHeader(L"Content-type:application/x-www-form-urlencoded/r/n"); //Testdata CrackedUrlcrackedUrl(L"http://www.easy-creator.net/test2/add.asp"); CStringAstrPostData("value1=10&value2=14"); //Opensession. hSession=OpenSession(L"HttpPostbyl_zhaohui@163.com"); if(hSession==NULL){ printf("Error:Opensession!/n"); return-1; } //Connect. hConnect=Connect(hSession,crackedUrl.GetHostName(),crackedUrl.GetPort()); if(hConnect==NULL){ printf("Error:Connectfailed!/n"); return-1; } //Openrequest. hRequest=OpenRequest(hConnect,L"POST",crackedUrl.GetPath(),crackedUrl.GetScheme()); if(hRequest==NULL){ printf("Error:OpenRequestfailed!/n"); return-1; } //Addrequestheader. if(!AddRequestHeaders(hRequest,strHeader)){ printf("Error:AddRequestHeadersfailed!/n"); return-1; } //Sendpostdata. if(!SendRequest(hRequest,(constchar*)strPostData,strPostData.GetLength())){ printf("Error:SendRequestfailed!/n"); return-1; } //Endrequest if(!EndRequest(hRequest)){ printf("Error:EndRequestfailed!/n"); return-1; } charszBuf[BUF_SIZE+1]; DWORDdwSize=0; szBuf[0]=0; //Queryheaderinfo. #ifdefUSE_WINHTTP intcontextLengthId=WINHTTP_QUERY_CONTENT_LENGTH; intstatusCodeId=WINHTTP_QUERY_STATUS_CODE; intstatusTextId=WINHTTP_QUERY_STATUS_TEXT; #else intcontextLengthId=HTTP_QUERY_CONTENT_LENGTH; intstatusCodeId=HTTP_QUERY_STATUS_CODE; intstatusTextId=HTTP_QUERY_STATUS_TEXT; #endif dwSize=BUF_SIZE; if(QueryInfo(hRequest,contextLengthId,szBuf,&dwSize)){ szBuf[dwSize]=0; printf("Contentlength:[%s]/n",szBuf); } dwSize=BUF_SIZE; if(QueryInfo(hRequest,statusCodeId,szBuf,&dwSize)){ szBuf[dwSize]=0; printf("Statuscode:[%s]/n",szBuf); } dwSize=BUF_SIZE; if(QueryInfo(hRequest,statusTextId,szBuf,&dwSize)){ szBuf[dwSize]=0; printf("Statustext:[%s]/n",szBuf); } //readdata. for(;;){ dwSize=BUF_SIZE; if(ReadData(hRequest,szBuf,dwSize,&dwSize)==FALSE){ break; } if(dwSize<=0){ break; } szBuf[dwSize]=0; printf("%s/n",szBuf);//Outputvalue=value1+value2 } CloseInternetHandle(hRequest); CloseInternetHandle(hConnect); CloseInternetHandle(hSession); return0; }
相关文章推荐
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现HTTP访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http訪问
- 使用WinINet和WinHTTP实现Http訪问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http訪问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http訪问
- 使用WinINet和WinHTTP实现Http訪问
- 使用WinINet和WinHTTP实现Http访问
- 使用WinINet和WinHTTP实现Http访问