string CNet::GetUrlHost(string strUrl)
{
string strRtn;
if(strUrl.empty())
return "";
int length = strUrl.length();
int i=0;
int j=0;
for(;i<length;i++)
{
if(strUrl.at(i) == '/')
{
j++;
}
if(j == 3)
break;
}
strRtn = strUrl.substr(0,i);
length = strRtn.length();
int rPos = strRtn.rfind('/');
strRtn = strRtn.substr(rPos+1,length);
return strRtn;
}
string CNet::GetUrlOther(string strUrl)
{
string strRtn;
if(strUrl.empty())
return "";
int length = strUrl.length();
int i=0;
int j=0;
for(;i<length;i++)
{
if(strUrl.at(i) == '/')
{
j++;
}
if(j == 3)
break;
}
strRtn = strUrl.substr(i,length);
return strRtn;
}
void CNet::GetHttp(string strUrl,string strPost,BOOL bIsShow,BOOL bIsKeepAlive)
{
OutputDebugString(_T("http开始了!"));
if(strUrl.empty())
{
cout<<"输入的url为空!"<<endl;
return;
}
HINTERNET hInternet = InternetOpen( _T("Testing"),
INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY,NULL, NULL, 0 ); //初始化WinINet
if(hInternet == NULL)
{
cout<<"WinINet初始化失败!"<<endl;
return;
}
string strCntName = GetUrlHost(strUrl);
HINTERNET hConnect = InternetConnect(hInternet, stringToLPCWSTR(strCntName), INTERNET_DEFAULT_HTTP_PORT,
NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); //连接服务器
if(hConnect == NULL)
{
cout<<"连接服务器失败!"<<endl;
InternetCloseHandle(hInternet);
return;
}
string strOther = GetUrlOther(strUrl);
strOther.append("\r\n");
HINTERNET hOpenRequest;
if(strPost.empty())
{
hOpenRequest = HttpOpenRequestA(hConnect, "GET",strOther.c_str() , ("HTTP/1.1"), NULL,
(LPCSTR*)"*/*", INTERNET_FLAG_DONT_CACHE, 1); //创建http请求 post
}
else
{
hOpenRequest = HttpOpenRequestA(hConnect, "POST",strOther.c_str() , ("HTTP/1.1"), NULL,
(LPCSTR*)"*/*", INTERNET_FLAG_DONT_CACHE, 1); //创建http请求 post
}
if(hOpenRequest == NULL)
{
cout<<"创建http请求失败!"<<endl;
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return;
}
//添加请求头信息,keepalive "Connection: keep-alive"
//长连接
if(bIsKeepAlive == TRUE)
{
LPCSTR header= "Connection: keep-alive/r/n";
SIZE_T len = strlen(header);
HttpAddRequestHeadersA(hOpenRequest,header,len,NULL);
}
BOOL bRequest;
if(strPost.empty())
{
bRequest = HttpSendRequestA( hOpenRequest, NULL,0, NULL,0);
}
else
{
//post 发送数据
DWORD dwSize = (strPost.empty()) ? 0 : strlen(strPost.c_str());
bRequest = HttpSendRequestA( hOpenRequest, NULL,0, (LPVOID)strPost.c_str(),dwSize); //发送http请求
}
int n = GetLastError();
if(bRequest == FALSE)
{
cout<<"发送http请求失败!"<<endl;
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
InternetCloseHandle(hOpenRequest);
return;
}
char szBuffer[1024] = {0};
DWORD dwByteRead = 0;
while (InternetReadFile(hOpenRequest, szBuffer, sizeof(szBuffer), &dwByteRead) && dwByteRead > 0)
{
if(bIsShow == TRUE)
{
cout<<szBuffer<<endl;
ZeroMemory(szBuffer, dwByteRead);
}
}
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
InternetCloseHandle(hOpenRequest);
OutputDebugString(_T("http结束了!"));
}
这里实现了get方法和post方法,post方法可以提交数据,strPost代表的提交的数据,通过wireshark抓包分析可知,
数据上传成功,get方法下实现了keepalive(原理是对请求头添加信息 keepalive\r\n,可以开启长连接,当然是否开启成功还是要看服务器是否支持)