1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110 |
- #include "StdAfx.h"
- #include "HTTP.h"
- #include "CodePageConvert.h"
- CDNSMap CHTTP::m_mapDNS; //DNS缓存表
- CHTTP::CHTTP(void)
- {
- m_pchRecvData = NULL;
- m_nDataSize = 0;
- }
- CHTTP::~CHTTP(void)
- {
- //释放接收的数据
- if (m_pchRecvData != NULL)
- {
- free(m_pchRecvData);
- m_pchRecvData = NULL;
- }
- m_nDataSize = 0;
- }
- int CHTTP::Init(void)
- {
- m_strURL = "";
- m_strHeader = "";
- m_bPost = false;
- m_strPostData = "";
- m_strWait = "";
- m_bNeedHeader = "";
- m_uiCodePage = CP_ACP;
- m_strPtl = "";
- m_strDomain = "";
- m_strPath = "";
- m_nPort = 8000;
- m_nPtlTailPos = string::npos;
- m_nDomainTailPos = string::npos;
- m_nConnTimeoutBak = m_nConnTimeout = HTTP::CONN_TIMEOUT_DEFAULT;
- m_nSendTimeoutBak = m_nSendTimeout = 100000;
- m_nRecvTimeoutBak = m_nRecvTimeout = 100000;
- m_listCookies.clear();
- m_strRecvData = "";
- m_nHeaderLen = -1;
- m_nBodyLen = -1;
- m_inputs = nullptr;
- m_bStartup = false;
- m_socket = INVALID_SOCKET;
- return 0;
- }
- /******************************************************************************
- HTTP的GET操作
- ******************************************************************************/
- int CHTTP::Get(string & strHTML, string strURL
- , string strHeader
- , string strWait, bool bNeedHeader)
- {
- m_strURL = strURL;
- m_strHeader = strHeader;
- m_bPost = false;
- m_strPostData = "";
- m_strWait = strWait;
- m_bNeedHeader = bNeedHeader;
- //获取HTML字符串
- int nGetHTMLStr = _GetHTMLStr(strHTML);
- if (nGetHTMLStr != 0)
- {
- return nGetHTMLStr;
- }
- return 0;
- }
- /******************************************************************************
- HTTP的POST操作
- ******************************************************************************/
- int CHTTP::Post(string & strHTML, string strURL, string strPostData
- , string strHeader
- , string strWait, bool bNeedHeader)
- {
- m_strURL = strURL;
- m_strHeader = strHeader;
- m_bPost = true;
- m_strPostData = strPostData;
- m_inputs = nullptr;
- m_strWait = strWait;
- m_bNeedHeader = bNeedHeader;
- //获取HTML字符串
- int nGetHTMLStr = _GetHTMLStr(strHTML);
- if (nGetHTMLStr != 0)
- {
- return nGetHTMLStr;
- }
- return 0;
- }
- /******************************************************************************
- HTTP的POST操作
- ******************************************************************************/
- int CHTTP::PostFile(string & strHTML, string strURL, std::vector<CInputFiled*>& inputs
- , string strHeader
- , string strWait , bool bNeedHeader )
- {
- m_strURL = strURL;
- m_strHeader = strHeader;
- m_bPost = true;
- m_strPostData = "";
- m_inputs = &inputs;
- m_strWait = strWait;
- m_bNeedHeader = bNeedHeader;
- //获取HTML字符串
- int nGetHTMLStr = _GetHTMLStr(strHTML);
- if (nGetHTMLStr != 0)
- {
- return nGetHTMLStr;
- }
- }
- /******************************************************************************
- GET图片数据
- ******************************************************************************/
- int CHTTP::GetImg(char * & pchImgData, int & nImgSize
- , string strURL, string strHeader)
- {
- m_strURL = strURL;
- m_strHeader = strHeader;
- m_bPost = false;
- m_strPostData = "";
- m_strWait = "";
- m_bNeedHeader = false;
- //执行HTTP操作
- int nExecute = _Execute();
- if (nExecute != 0)
- {
- return nExecute;
- }
- //返回图片数据
- if (m_pchRecvData == NULL)
- {
- return HTTP::GET_IMG_DATA_NULL;
- }
- if (m_nDataSize <= 0)
- {
- return HTTP::GET_IMG_SIZE_INVALID;
- }
- pchImgData = m_pchRecvData;
- nImgSize = m_nDataSize;
- return 0;
- }
- /******************************************************************************
- 设置超时时间
- ******************************************************************************/
- void CHTTP::SetTimeout(int nConnTimeout, int nSendTimeout, int nRecvTimeout)
- {
- //先备份值
- m_nConnTimeoutBak = m_nConnTimeout;
- m_nSendTimeoutBak = m_nSendTimeout;
- m_nRecvTimeoutBak = m_nRecvTimeout;
- //修改值
- m_nConnTimeout = nConnTimeout;
- m_nSendTimeout = nSendTimeout;
- m_nRecvTimeout = nRecvTimeout;
- }
- /******************************************************************************
- 恢复上次设置的超时时间
- ******************************************************************************/
- void CHTTP::SetTimeoutBack(void)
- {
- m_nConnTimeout = m_nConnTimeoutBak;
- m_nSendTimeout = m_nSendTimeoutBak;
- m_nRecvTimeout = m_nRecvTimeoutBak;
- }
- /******************************************************************************
- 添加一个Cookie项
- ******************************************************************************/
- int CHTTP::AddCookie(string strCookie)
- {
- if (strCookie == "")
- {
- return HTTP::ADD_COOKIE_STRING_COOKIE_NULL;
- }
- //分解此Cookie
- HTTP::SCookie sCookie;
- int nParseCookie = _ParseCookieStr(sCookie, strCookie);
- if (nParseCookie != 0)
- {
- return nParseCookie;
- }
- if (sCookie.strName == "")
- {
- return HTTP::ADD_COOKIE_STRING_NAME_NULL;
- }
- //添加到Cookie列表
- int nAddCookie = _AddCookie(sCookie);
- if (nAddCookie != 0)
- {
- return nAddCookie;
- }
- return 0;
- }
- /******************************************************************************
- 获取Cookies字符串
- ******************************************************************************/
- string CHTTP::GetCookies(bool bOnlyNameValue)
- {
- string strCookies = "";
- //分隔符,默认为;;,如果只需要Cookie名和值,则为;
- string strSplit = ";; ";
- if (bOnlyNameValue)
- {
- strSplit = "; ";
- }
- //遍历Cookies表
- int nListSize = m_listCookies.size();
- for (int i = 0; i < nListSize; i++)
- {
- //提取一条Cookie
- HTTP::SCookie const & sCookie = m_listCookies[i];
- string strCookie = "";
- strCookie += sCookie.strName + "=" + sCookie.strValue;
- if (!bOnlyNameValue)
- {
- if (sCookie.strPath != "")
- {
- strCookie += "; path=" + sCookie.strPath;
- }
- if (sCookie.strDomain != "")
- {
- strCookie += "; domain=" + sCookie.strDomain;
- }
- }
- //添加到Cookies字符串中
- strCookies += (strCookies == "") ? "" : strSplit;
- strCookies += strCookie;
- }
- return strCookies;
- }
- /******************************************************************************
- 设置Cookies
- ******************************************************************************/
- int CHTTP::SetCookies(string strCookies)
- {
- //清空Cookies表
- m_listCookies.clear();
- if (strCookies == "")
- {
- return 0;
- }
- //默认用 ;; 分割
- string strSplit = ";;";
- //如果找不到分割字符串,则用 ; 分割
- if (strCookies.find(strSplit) == string::npos)
- {
- strSplit = ";";
- }
- //分割字符串
- vector<string> listCookies;
- _SplitStr(listCookies, strCookies, strSplit);
- //添加每一个Cookies
- int nListLen = listCookies.size();
- for (int i = 0; i < nListLen; i++)
- {
- string strCookie = listCookies[i];
- if (strCookie != "")
- {
- int nAddCookie = AddCookie(strCookie);
- if (nAddCookie != 0)
- {
- return nAddCookie;
- }
- }
- }
- return 0;
- }
- /******************************************************************************
- 设置编码方式
- ******************************************************************************/
- void CHTTP::SetCodePage(UINT uiCodePage)
- {
- m_uiCodePage = uiCodePage;
- }
- /******************************************************************************
- 清除DNS缓存
- ******************************************************************************/
- int CHTTP::ClearDNS(void)
- {
- //清空DNS缓存表
- int nClearDNS = m_mapDNS.ClearDNS();
- if (nClearDNS != 0)
- {
- return nClearDNS;
- }
- return 0;
- }
- /******************************************************************************
- 执行HTTP操作
- ******************************************************************************/
- int CHTTP::_Execute(void)
- {
- //分解URL
- int nParseURL = _ParseURL();
- if (nParseURL != 0)
- {
- return nParseURL;
- }
- //开始访问
- int nStartVisit = _StartVisitFile();
- //结束访问,保证句柄释放,所以放到这里执行
- int nEndVisit = _EndVisit();
- if (nStartVisit != 0)
- {
- return nStartVisit;
- }
- if (nEndVisit != 0)
- {
- return nEndVisit;
- }
- return 0;
- }
- /******************************************************************************
- 获取HTML字符串
- ******************************************************************************/
- int CHTTP::_GetHTMLStr(string & strHTML)
- {
- //执行HTTP操作
- int nExecute = _Execute();
- if (nExecute != 0)
- {
- return nExecute;
- }
- //编码转换
- int nEncodeRecvStr = _EncodeRecvStr();
- if (nEncodeRecvStr != 0)
- {
- return nEncodeRecvStr;
- }
- //返回值
- strHTML = m_strRecvData;
- return 0;
- }
- /******************************************************************************
- 分解URL
- ******************************************************************************/
- int CHTTP::_ParseURL(void)
- {
- //获取协议
- int nCutURLPtl = _CutURLPtl();
- if (nCutURLPtl != 0)
- {
- return nCutURLPtl;
- }
- //获取域名
- int nCutURLDomain = _CutURLDomain();
- if (nCutURLDomain != 0)
- {
- return nCutURLDomain;
- }
- //提取路径
- int nCutURLPath = _CutURLPath();
- if (nCutURLPath != 0)
- {
- return nCutURLPath;
- }
- return 0;
- }
- /******************************************************************************
- 连接服务器
- ******************************************************************************/
- int CHTTP::_ConnServer(void)
- {
- //启动并创建套接字
- int nStartupCreateSocket = _StartupCreateSocket();
- if (nStartupCreateSocket != 0)
- {
- return nStartupCreateSocket;
- }
- //填写地址信息
- sockaddr_in addr = {0};
- int nFillAddrInfo = _FillAddrInfo(addr);
- if (nFillAddrInfo != 0)
- {
- return nFillAddrInfo;
- }
- //带超时的连接
- int nConnWithTimeout = _ConnWithTimeout(addr);
- if (nConnWithTimeout != 0)
- {
- return nConnWithTimeout;
- }
- //设置套接字的超时
- int nSetSocketTimeout = _SetSocketTimeout();
- if (nSetSocketTimeout != 0)
- {
- return nSetSocketTimeout;
- }
- return 0;
- }
- /******************************************************************************
- 发送数据
- ******************************************************************************/
- int CHTTP::_SendData(void)
- {
- string strSendData = "";
- //构造请求头
- string strHeader = _MakeHeader();
- //添加请求头,添加头和尾
- if (m_strPath == "")
- {
- return HTTP::SEND_DATA_PATH_NULL;
- }
- strSendData += (m_bPost ? "POST " : "GET ") + m_strPath + " HTTP/1.1\r\n";
- strSendData += strHeader;
- strSendData += "\r\n\r\n";
- //编码POST数据
- if (m_bPost)
- {
- int nEncodePostData = _EncodePostData();
- if (nEncodePostData != 0)
- {
- return nEncodePostData;
- }
- strSendData += m_strPostData;
- }
- //发送数据
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::SEND_DATA_INVALID_SOCKET;
- }
- if (send(m_socket, strSendData.c_str(), strSendData.length(), 0)
- == SOCKET_ERROR)
- {
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- return 0;
- }
- /******************************************************************************
- 接收数据
- ******************************************************************************/
- int CHTTP::_RecvData(void)
- {
- //接收响应数据
- int nRecvResponseData = _RecvResponseData();
- if (nRecvResponseData != 0)
- {
- return nRecvResponseData;
- }
- //提取Cookies
- int nGetResponseCookies = _GetResponseCookies();
- if (nGetResponseCookies != 0)
- {
- return nGetResponseCookies;
- }
- //剔除响应数据的头部
- int nRejectHeader = _RejectHeader();
- if (nRejectHeader != 0)
- {
- return nRejectHeader;
- }
- return 0;
- }
- /******************************************************************************
- 剔除响应数据的头部
- ******************************************************************************/
- int CHTTP::_RejectHeader(void)
- {
- //如果需要响应头,则不剔除
- if (m_bNeedHeader)
- {
- return 0;
- }
- //剔除接收数据的响应头
- if (m_nDataSize <= 0)
- {
- return HTTP::REJECT_HEADER_DATA_SIZE_INVALID;
- }
- if (m_nHeaderLen <= 0)
- {
- return HTTP::REJECT_HEADER_HEADER_LEN_INVALID;
- }
- if (m_pchRecvData == NULL)
- {
- return HTTP::REJECT_HEADER_RECV_DATA_NULL;
- }
- m_nDataSize -= m_nHeaderLen;
- memmove(m_pchRecvData, m_pchRecvData + m_nHeaderLen, m_nDataSize);
- //重新转换字符串
- int nTransDataToStr = _TransDataToStr();
- if (nTransDataToStr != 0)
- {
- return nTransDataToStr;
- }
- return 0;
- }
- /******************************************************************************
- 提取响应数据的Cookies
- ******************************************************************************/
- int CHTTP::_GetResponseCookies(void)
- {
- //提取响应头
- if (m_strRecvData == "")
- {
- return HTTP::GET_RESPONSE_COOKIES_RECV_DATA_NULL;
- }
- if (m_nHeaderLen <= 0)
- {
- return HTTP::GET_RESPONSE_COOKIES_HEADER_LEN_INVALID;
- }
- string strHeader = m_strRecvData.substr(0, m_nHeaderLen);
- if (strHeader == "")
- {
- return HTTP::GET_RESPONSE_COOKIES_HEADER_NULL;
- }
- //提取Cookies
- vector<string> listCookies;
- _SplitStr(listCookies, strHeader, "\r\n");
- int nListLen = listCookies.size();
- for (int i = 0; i < nListLen; i++)
- {
- string strCookie = listCookies[i];
- if (strCookie == ""
- || strCookie.find("Set-Cookie:") == string::npos)
- {
- continue;
- }
- _ReplaceString(strCookie, "Set-Cookie:", "");
- if (strCookie != "")
- {
- int nAddCookie = AddCookie(strCookie);
- if (nAddCookie != 0)
- {
- return nAddCookie;
- }
- }
- }
- return 0;
- }
- /******************************************************************************
- 接收响应数据
- ******************************************************************************/
- int CHTTP::_RecvResponseData(void)
- {
- //接收数据初始化
- m_nDataSize = 0;
- m_strRecvData = "";
- m_nHeaderLen = -1;
- m_nBodyLen = -1;
- //当接收没有结束时,循环接收数据
- while (!_IsEndRecv())
- {
- //接收一次数据
- int nRecvEachData = _RecvEachData();
- if (nRecvEachData != 0)
- {
- return nRecvEachData;
- }
- //把收到的数据转换成字符串
- int nTransDataToStr = _TransDataToStr();
- if (nTransDataToStr != 0)
- {
- return nTransDataToStr;
- }
- }
- return 0;
- }
- /******************************************************************************
- 一次一次接收数据
- ******************************************************************************/
- int CHTTP::_RecvEachData(void)
- {
- //申请内存
- if (m_nDataSize < 0)
- {
- return HTTP::RECV_EACH_DATA_SIZE_INVALID;
- }
- m_nDataSize += HTTP::RECV_BUF_SIZE;
- char * pchRecvData = (char *)realloc(m_pchRecvData, m_nDataSize);
- if (pchRecvData == NULL)
- {
- return HTTP::RECV_EACH_DATA_MALLOC_FAIL;
- }
- m_pchRecvData = pchRecvData;
- //接收数据
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::RECV_EACH_DATA_INVALID_SOCKET;
- }
- int nRecv = recv(m_socket
- , m_pchRecvData + m_nDataSize - HTTP::RECV_BUF_SIZE
- , HTTP::RECV_BUF_SIZE, 0);
- if (nRecv == 0)
- {
- return HTTP::RECV_EACH_DATA_CONN_CLOSE;
- }
- if (nRecv < 0
- || nRecv == SOCKET_ERROR)
- {
- return HTTP::RECV_EACH_DATA_RECV_FAIL;
- }
- //修改接收到的数据大小
- m_nDataSize -= HTTP::RECV_BUF_SIZE - nRecv;
- return 0;
- }
- /******************************************************************************
- 是否结束接收
- ******************************************************************************/
- bool CHTTP::_IsEndRecv(void)
- {
- //获取正文长度
- _GetBodyLen();
- //如果指定了等待字符串,则是否结束接收由这个决定
- if (m_strWait != "")
- {
- return _CheckWaitStr();
- }
- //如果响应头还没接收完,则继续接收
- if (m_nHeaderLen == -1)
- {
- return false;
- }
- //如果没有指定正文长度,则结束接收
- if (m_nBodyLen == -1)
- {
- return true;
- }
- //指定了正文长度,则检测长度,长度达到则结束接收
- else if (m_nDataSize - m_nHeaderLen
- >= m_nBodyLen)
- {
- return true;
- }
- return false;
- }
- /******************************************************************************
- 获取响应数据正文长度
- ******************************************************************************/
- void CHTTP::_GetBodyLen(void)
- {
- //如果响应头已经接收完毕,则直接返回
- if (m_nHeaderLen != -1)
- {
- return;
- }
- //查找响应头结束符
- if (m_strRecvData == "")
- {
- return;
- }
- string::size_type nHeaderEndPos = m_strRecvData.find("\r\n\r\n");
- if (nHeaderEndPos == string::npos)
- {
- return;
- }
- m_nHeaderLen = nHeaderEndPos + strlen("\r\n\r\n");
- //截取响应头
- string strHeader = m_strRecvData.substr(0, m_nHeaderLen);
- if (strHeader == "")
- {
- return;
- }
- //获取HTTP响应包正文的长度
- string strLength = _CutStr(strHeader, "Content-Length:", "\r\n");
- if (strLength == "")
- {
- return;
- }
- m_nBodyLen = atoi(strLength.c_str());
- }
- /******************************************************************************
- 开始访问
- ******************************************************************************/
- int CHTTP::_StartVisit(void)
- {
- //连接服务器
- int nConnServer = _ConnServer();
- if (nConnServer != 0)
- {
- return nConnServer;
- }
- //发送数据
- int nSendData = _SendData();
- if (nSendData != 0)
- {
- return nSendData;
- }
- //接收数据
- int nRecvData = _RecvData();
- if (nRecvData != 0)
- {
- return nRecvData;
- }
- return 0;
- }
- /******************************************************************************
- 开始访问
- ******************************************************************************/
- int CHTTP::_StartVisitFile(void)
- {
- //连接服务器
- int nConnServer = _ConnServer();
- if (nConnServer != 0)
- {
- return nConnServer;
- }
- //发送数据
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::SEND_DATA_INVALID_SOCKET;
- }
- //发送数据
- {
- //发送数据差别较大比较
- string strSendData = "";
- //构造请求头
- string strHeader = "POST ";
- strHeader += m_strPath;
- strHeader += " HTTP/1.1\r\n";
- string boundary_value = ("---------------------------7b4a6d158c9");
- string boundary = ("--") + boundary_value;
- string end_boundary = boundary + ("--");
- string end_filed = ("--");
- //添加基本请求头
- strHeader +=
- "Host: " + m_strDomain +
- "\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)";
- strHeader += "User-Agent: Mozilla/4.0\r\n";
- strHeader += "Accept-Language: zh-cn\r\n";
- strHeader += "Connection: Keep-Alive\r\n";
- strHeader += "Accept: */*\r\n";
- strHeader += "Content-Type: multipart/form-data; charset=\"utf-8\"; boundary=---------------------------7b4a6d158c9\r\n";
-
-
- //指定请求头
- if (m_strHeader != "")
- {
- strHeader += "\r\n";
- strHeader += m_strHeader;
- }
- vector<char*> ff;
- vector<int> ff_len;
- //编码POST数据
- DWORD dwTotalRequestLength = 0;
-
- for (int i = 0; i<(*m_inputs).size(); i++)
- {
- CString field;
- char * filed_str = NULL;
- int filedLength = 0;
- if ((*m_inputs)[i]->GetType() == INPUT_FILED_VALUE){
- field.Format(_T("%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n"), _T("-----------------------------7b4a6d158c9"), (*m_inputs)[i]->GetFiledName(), (*m_inputs)[i]->GetFiledValue());
- filedLength = WideCharToMultiByte(CP_UTF8, 0, field, -1, NULL, 0, NULL, NULL);
- filed_str = new char[filedLength];
- WideCharToMultiByte(CP_UTF8, 0, field, -1, filed_str, filedLength, NULL, NULL);
- dwTotalRequestLength += (filedLength - 1);
- }
- else{
- field.Format(_T("%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: image/jpeg\r\n\r\n"), _T("-----------------------------7b4a6d158c9"), (*m_inputs)[i]->GetFiledName(), (*m_inputs)[i]->GetFiledValue());
- filedLength = WideCharToMultiByte(CP_UTF8, 0, field, -1, NULL, 0, NULL, NULL);
- filed_str = new char[filedLength];
- WideCharToMultiByte(CP_UTF8, 0, field, -1, filed_str, filedLength, NULL, NULL);
- dwTotalRequestLength += (filedLength - 1);
- dwTotalRequestLength +=(*m_inputs)[i]->DataSize();
- dwTotalRequestLength += 2;
- }
- ff.push_back(filed_str);
- ff_len.push_back(filedLength);
- }
- char * filed_str = NULL;
- CString field = _T("-----------------------------7b4a6d158c9--");
- int endLength = WideCharToMultiByte(CP_UTF8, 0, field, -1, NULL, 0, NULL, NULL);
- filed_str = new char[endLength];
- WideCharToMultiByte(CP_UTF8, 0, field, -1, filed_str, endLength, NULL, NULL);
- dwTotalRequestLength += (endLength - 1);
- //strHeader += "Content-Length: 2951835 ";
- //strHeader += ("\r\nContent-Type: multipart/form-data; boundary=" + boundary_value);
- char temp[64] = { 0 };
- //注意下面这个参数Content-Length,这个参数值是:http请求头长度+请求尾长度+文件总长度
- sprintf(temp, "Content-Length: %d\r\n\r\n", dwTotalRequestLength);
- strHeader += temp;
-
- if (send(m_socket, strHeader.c_str(), strHeader.length(), 0)
- == SOCKET_ERROR)
- {
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- for (int i = 0; i<(*m_inputs).size(); i++)
- {
- if ((*m_inputs)[i]->GetType() == INPUT_FILED_VALUE){
- if (send(m_socket, ff[i], ff_len[i] - 1, 0) == SOCKET_ERROR)
- {
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- }
- else{
- if (send(m_socket, ff[i], ff_len[i] - 1, 0) == SOCKET_ERROR)
- {
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- CInputFiled* input = (*m_inputs)[i];
- const int buffer_size = 4 * 1024;
- char buffer[buffer_size];
- int len;
- input->Open();
- while ((len = input->Read(buffer, buffer_size))>0){
- if (send(m_socket, buffer, len, 0) == SOCKET_ERROR)
- {
- int fff = WSAGetLastError();
- input->Close();
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- }
- input->Close();
- if (send(m_socket, "\r\n", 2, 0) == SOCKET_ERROR)
- {
- input->Close();
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- }
- }
- if (send(m_socket, filed_str, endLength, 0) == SOCKET_ERROR)
- {
- return HTTP::SEND_DATA_SEND_FAIL;
- }
- }
- //接收数据
- int nRecvData = _RecvData();
- if (nRecvData != 0)
- {
- return nRecvData;
- }
- return 0;
- }
- /******************************************************************************
- 结束访问
- ******************************************************************************/
- int CHTTP::_EndVisit(void)
- {
- //关闭套接字
- if (m_socket != INVALID_SOCKET)
- {
- if (closesocket(m_socket) != 0)
- {
- return HTTP::END_VISIT_CLOSE_FAIL;
- }
- m_socket = INVALID_SOCKET;
- }
- //清空套接字
- if (m_bStartup)
- {
- if (WSACleanup() != 0)
- {
- return HTTP::END_VISIT_CLEAN_FAIL;
- }
- }
- return 0;
- }
- /******************************************************************************
- 把数据转换成字符串
- ******************************************************************************/
- int CHTTP::_TransDataToStr(void)
- {
- //没有数据
- if (m_nDataSize == 0)
- {
- m_strRecvData = "";
- return 0;
- }
- //申请多一个字节的内存,存放结束符
- if (m_nDataSize < 0)
- {
- return HTTP::TRANS_DATA_TO_STR_SIZE_INVALID;
- }
- if (m_pchRecvData == NULL)
- {
- return HTTP::TRANS_DATA_TO_STR_DATA_NULL;
- }
- char * pchRecvData = (char *)realloc(m_pchRecvData, m_nDataSize + 1);
- if (pchRecvData == NULL)
- {
- return HTTP::TRANS_DATA_TO_STR_REBUF_FAIL;
- }
- m_pchRecvData = pchRecvData;
- //添加字符串结束符,变成字符串
- m_pchRecvData[m_nDataSize] = '\0';
- m_strRecvData = m_pchRecvData;
- if (m_strRecvData == "")
- {
- return HTTP::TRANS_DATA_TO_STR_STR_NULL;
- }
- return 0;
- }
- /******************************************************************************
- 把接收到的字符串编码转换
- ******************************************************************************/
- int CHTTP::_EncodeRecvStr(void)
- {
- if (m_strRecvData == "")
- {
- return 0;
- }
- //对UTF8编码
- if (m_uiCodePage == CP_UTF8)
- {
- int nTransCodePage = _TransCodePage(
- m_strRecvData, CP_ACP, m_uiCodePage);
- if (nTransCodePage != 0)
- {
- return nTransCodePage;
- }
- if (m_strRecvData == "")
- {
- return HTTP::ENCODE_RECV_STR_FAIL;
- }
- }
- return 0;
- }
- /******************************************************************************
- 检测等待字符串是否出现
- ******************************************************************************/
- bool CHTTP::_CheckWaitStr(void)
- {
- if (m_strWait == "")
- {
- return false;
- }
- if (m_strRecvData == "")
- {
- return false;
- }
- if (m_strRecvData.find(m_strWait) == string::npos)
- {
- return false;
- }
- return true;
- }
- /******************************************************************************
- 编码POST数据
- ******************************************************************************/
- int CHTTP::_EncodePostData(void)
- {
- //对UTF8编码
- if (m_uiCodePage == CP_UTF8)
- {
- if (m_strPostData == "")
- {
- return 0;
- }
- int nTransCodePage = _TransCodePage(
- m_strPostData, m_uiCodePage, CP_ACP);
- if (nTransCodePage != 0)
- {
- return nTransCodePage;
- }
- if (m_strPostData == "")
- {
- return HTTP::ENCODE_POST_DATA_FAIL;
- }
- }
- return 0;
- }
- /******************************************************************************
- 获取IP地址
- ******************************************************************************/
- int CHTTP::_GetIPStr(wstring & strIP)
- {
- //获取IP字符串
- if (m_strDomain == "")
- {
- return HTTP::GET_IP_STR_DOMAIN_NULL;
- }
- string strGetIP = "";
- int nGetIPStr = m_mapDNS.GetIPStr(strGetIP, m_strDomain);
- if (nGetIPStr != 0)
- {
- return nGetIPStr;
- }
- if (strGetIP == "")
- {
- return HTTP::GET_IP_STR_IP_NULL;
- }
- //转换成宽字符
- if (!MBToWC(strIP, strGetIP, CP_ACP))
- {
- return HTTP::GET_IP_STR_IPW_FAIL;
- }
- if (strIP == L"")
- {
- return HTTP::GET_IP_STR_IPW_NULL;
- }
- return 0;
- }
- /******************************************************************************
- 编码转换
- ******************************************************************************/
- int CHTTP::_TransCodePage(string & strTrans
- , UINT uiDstCodePage, UINT uiSrcCodePage)
- {
- //先把源串转换为宽字符串
- if (strTrans == "")
- {
- return 0;
- }
- wstring strWC = L"";
- if (!MBToWC(strWC, strTrans, uiSrcCodePage))
- {
- return HTTP::TRANS_CODE_PAGE_WC_FAIL;
- }
- if (strWC == L"")
- {
- return HTTP::TRANS_CODE_PAGE_WC_NULL;
- }
- //再把宽字符串转换为目标串
- if (!WCToMB(strTrans, strWC, uiDstCodePage))
- {
- return HTTP::TRANS_CODE_PAGE_DST_FAIL;
- }
- if (strTrans == "")
- {
- return HTTP::TRANS_CODE_PAGE_DST_NULL;
- }
- return 0;
- }
- /******************************************************************************
- 构造请求头
- ******************************************************************************/
- string CHTTP::_MakeHeader(void)
- {
- string strHeader = "";
- //添加基本请求头
- strHeader +=
- "Host: " + m_strDomain +
- "\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)";
- //指定请求头
- if (m_strHeader != "")
- {
- strHeader += "\r\n";
- strHeader += m_strHeader;
- }
- //POST请求头
- if (m_bPost)
- {
- strHeader += "\r\n";
- strHeader += "Content-Type: application/x-www-form-urlencoded";
- strHeader += "\r\n";
- strHeader += "Content-Length: ";
- char achBuf[12] = {0};
- _itoa_s(m_strPostData.length(), achBuf, sizeof(achBuf), 10);
- strHeader += achBuf;
- }
- //Cookies
- string strCookies = _MakeCookiesString();
- if (strCookies != "")
- {
- strHeader += "\r\n";
- strHeader += strCookies;
- }
- return strHeader;
- }
- /******************************************************************************
- 截取URL的协议部分
- ******************************************************************************/
- int CHTTP::_CutURLPtl()
- {
- //定位协议冒号和反斜杠
- if (m_strURL == "")
- {
- return HTTP::CUT_URL_PTL_URL_NULL;
- }
- m_nPtlTailPos = m_strURL.find("://");
- if (m_nPtlTailPos == string::npos)
- {
- return HTTP::CUT_URL_PTL_PTL_TAIL_POS;
- }
- //截取协议
- m_strPtl = m_strURL.substr(0, m_nPtlTailPos);
- if (m_strPtl == "")
- {
- return HTTP::CUT_URL_PTL_PTL_NULL;
- }
- //把协议转换成小写
- _ToLower(m_strPtl);
- //协议默认的端口
- if (m_strPtl == "http")
- {
- m_nPort = 80;
- }
- else
- {
- return HTTP::CUT_URL_PTL_PTL_UNKNOW;
- }
- return 0;
- }
- /******************************************************************************
- 截取URL的域名部分
- ******************************************************************************/
- int CHTTP::_CutURLDomain()
- {
- //定位域名后面的反斜杠
- if (m_nPtlTailPos == string::npos)
- {
- return HTTP::CUT_URL_DOMAIN_PTL_TAIL_POS;
- }
- string::size_type nDomainHeadPos = m_nPtlTailPos + strlen("://");
- if (m_strURL == "")
- {
- return HTTP::CUT_URL_DOMAIN_URL_NULL;
- }
- if (nDomainHeadPos >= m_strURL.length())
- {
- return HTTP::CUT_URL_DOMAIN_DOMAIN_HEAD_POS;
- }
- m_nDomainTailPos = m_strURL.find("/", nDomainHeadPos);
- if (m_nDomainTailPos == string::npos)
- {
- return HTTP::CUT_URL_DOMAIN_DOMAIN_TAIL_POS;
- }
- //截取域名
- m_strDomain = m_strURL.substr(nDomainHeadPos
- , m_nDomainTailPos - nDomainHeadPos);
- if (m_strDomain == "")
- {
- return HTTP::CUT_URL_DOMAIN_DOMAIN_NULL;
- }
- //处理域名中包含端口号的情况
- int nProcessDomainPort = _ProcessDomainPort();
- if (nProcessDomainPort != 0)
- {
- return nProcessDomainPort;
- }
- return 0;
- }
- /******************************************************************************
- 处理域名中包含端口号的情况
- ******************************************************************************/
- int CHTTP::_ProcessDomainPort()
- {
- if (m_strDomain == "")
- {
- return HTTP::PROCESS_DOMAIN_PORT_DOMAIN_NULL;
- }
- //检测域名中是否指定了端口
- string::size_type nPortColonPos = m_strDomain.find(":");
- if (nPortColonPos != string::npos)
- {
- //截取端口号
- string::size_type nPortHeadPos = nPortColonPos + strlen(":");
- if (nPortHeadPos >= m_strDomain.length())
- {
- return HTTP::PROCESS_DOMAIN_PORT_PORT_POS;
- }
- string strPort = m_strDomain.substr(nPortHeadPos
- , m_strDomain.length() - nPortHeadPos);
- if (strPort == "")
- {
- return HTTP::PROCESS_DOMAIN_PORT_PORT_NULL;
- }
- //把端口号转换成整型
- m_nPort = (unsigned short)atol(strPort.c_str());
- if (m_nPort == 0)
- {
- return HTTP::PROCESS_DOMAIN_PORT_PORT_ZERO;
- }
- //重新截取域名
- m_strDomain = m_strDomain.substr(0, nPortColonPos);
- if (m_strDomain == "")
- {
- return HTTP::PROCESS_DOMAIN_PORT_DOMAIN_RECUT;
- }
- }
- return 0;
- }
- /******************************************************************************
- 截取URL的路径部分
- ******************************************************************************/
- int CHTTP::_CutURLPath(void)
- {
- if (m_strURL == "")
- {
- return HTTP::CUT_URL_PATH_URL_NULL;
- }
- if (m_nDomainTailPos == string::npos
- || m_nDomainTailPos >= m_strURL.length())
- {
- return HTTP::CUT_URL_PATH_DOMAIN_TAIL_POS;
- }
- m_strPath = m_strURL.substr(m_nDomainTailPos
- , m_strURL.length() - m_nDomainTailPos);
- if (m_strPath == "")
- {
- return HTTP::CUT_URL_PATH_PATH_NULL;
- }
- return 0;
- }
- /******************************************************************************
- 生成Cookies串
- ******************************************************************************/
- string CHTTP::_MakeCookiesString(void)
- {
- string strCookies = "";
- //遍历Cookies列表
- int nListLen = (int)m_listCookies.size();
- for (int i = 0; i < nListLen; i++)
- {
- //提取一条Cookie
- HTTP::SCookie const & sCookie = m_listCookies[i];
- if (sCookie.strName == ""
- || sCookie.strValue == "")
- {
- continue;
- }
- //判断这条Cookie是否匹配域名和路径属性
- if (_IsCookieMatch(sCookie))
- {
- //加入分隔符
- strCookies += (strCookies == "") ? "Cookie: " : "; ";
- //加入键值
- strCookies += sCookie.strName + "=" + sCookie.strValue;
- }
- }
- return strCookies;
- }
- /******************************************************************************
- 判断这条Cookie是否匹配域名和路径属性
- ******************************************************************************/
- bool CHTTP::_IsCookieMatch(HTTP::SCookie const & sCookie)
- {
- //判断是否匹配路径
- if (!_IsCookiePathMatch(sCookie.strPath))
- {
- return false;
- }
- //判断是否匹配域名
- if (!_IsCookieDomainMatch(sCookie.strDomain))
- {
- return false;
- }
- return true;
- }
- /******************************************************************************
- 截取字符串
- ******************************************************************************/
- string CHTTP::_CutStr(string strSource, string strHead, string strTail)
- {
- if (strSource == "")
- {
- return "";
- }
- //便于定位,剔除所有空格
- _ReplaceString(strSource, " ", "");
- if (strSource == "")
- {
- return "";
- }
- //便于定位,转换成小写
- string strSourceLow = strSource;
- string strHeadLow = strHead;
- string strTailLow = strTail;
- _ToLower(strSourceLow);
- _ToLower(strHeadLow);
- _ToLower(strTailLow);
- //定位字符串
- string::size_type nPos = 0;
- string::size_type nLen = 0;
- if (strSourceLow == "")
- {
- return "";
- }
- if (!_PosStr(nPos, nLen, strSourceLow, strHeadLow, strTailLow))
- {
- return "";
- }
- if (nPos < 0
- || nPos >= strSource.length()
- || nLen < 0)
- {
- return "";
- }
- //截取字符串
- return strSource.substr(nPos, nLen);
- }
- /******************************************************************************
- 定位字符串
- ******************************************************************************/
- bool CHTTP::_PosStr(string::size_type & nPos, string::size_type & nLen,
- string strSourceLow, string strHeadLow, string strTailLow)
- {
- if (strSourceLow == "")
- {
- return false;
- }
- //头定位
- string::size_type nHeadPos = strSourceLow.find(strHeadLow);
- if (nHeadPos == string::npos)
- {
- return false;
- }
- //内容定位
- string::size_type nValuePos = nHeadPos + strlen(strHeadLow.c_str());
- if (nValuePos >= strSourceLow.length())
- {
- return false;
- }
- //尾定位
- string::size_type nTailPos = strSourceLow.find(strTailLow, nValuePos);
- if (nTailPos == string::npos)
- {
- return false;
- }
- //如果尾定位字符串为空,则认为定位到源字符串最后
- if (strTailLow == "")
- {
- nTailPos = strSourceLow.length();
- }
- //返回定位结果
- nPos = nValuePos;
- if (nTailPos < nValuePos)
- {
- return false;
- }
- nLen = nTailPos - nValuePos;
- return true;
- }
- /******************************************************************************
- 判断这条Cookie路径是否匹配
- ******************************************************************************/
- bool CHTTP::_IsCookiePathMatch(string strCookiePath)
- {
- if (m_strPath == "")
- {
- return false;
- }
- //为空则默认匹配
- if (strCookiePath == "")
- {
- return true;
- }
- if (m_strPath.find(strCookiePath) != 0)
- {
- //找不到,肯定不匹配
- return false;
- }
- //获取Cookie路径最后一个字符
- int nCookiePathEndPos = (int)strCookiePath.length() - 1;
- if (nCookiePathEndPos < 0)
- {
- return false;
- }
- char chCookiePathEnd = strCookiePath[nCookiePathEndPos];
- //如果以 / 结尾,则匹配没问题了
- if (chCookiePathEnd == '/')
- {
- return true;
- }
- //检测后面还没匹配完的情况。比如:/ab和/abc,只匹配前面,但其实不匹配
- if (!_IsCookiePathMatchNext(strCookiePath))
- {
- return false;
- }
- return true;
- }
- /******************************************************************************
- 判断这条Cookie域名是否匹配
- ******************************************************************************/
- bool CHTTP::_IsCookieDomainMatch(string strCookieDomain)
- {
- if (m_strDomain == "")
- {
- return false;
- }
- //为空则默认匹配
- if (strCookieDomain == "")
- {
- return true;
- }
- string::size_type nDomainPos = m_strDomain.rfind(strCookieDomain);
- if (nDomainPos == string::npos)
- {
- //找不到,肯定不匹配
- return false;
- }
- //判断是否正好匹配到了最后面
- if (nDomainPos + strlen(strCookieDomain.c_str())
- == m_strDomain.size())
- {
- return true;
- }
- return false;
- }
- /******************************************************************************
- 判断这条Cookie路径的后面是否匹配,防止/ab与/abc匹配的情况。
- ******************************************************************************/
- bool CHTTP::_IsCookiePathMatchNext(string strCookiePath)
- {
- if (m_strPath == "")
- {
- return false;
- }
- //为空则默认匹配
- if (strCookiePath == "")
- {
- return true;
- }
- string::size_type nPathLen = m_strPath.size();
- string::size_type nCookiePathLen = strCookiePath.size();
- //后面还有东西,则需要检测
- if (nPathLen > nCookiePathLen)
- {
- //获取匹配后的下一个字符
- char chMatchNext = m_strPath[nCookiePathLen];
- //检测下一个字符
- if (chMatchNext != '/'
- && chMatchNext != '?'
- && chMatchNext != '#')
- {
- //后面并不匹配
- return false;
- }
- }
- return true;
- }
- /******************************************************************************
- 字符串替换
- ******************************************************************************/
- void CHTTP::_ReplaceString(string & strReplace, string strOld, string strNew)
- {
- string::size_type nFindStartPos = 0;
- string::size_type nFoundPos = string::npos;
- string::size_type nOldLen = strOld.length();
- string::size_type nNewLen = strNew.length();
- //要替换的字符串为空,没法替换
- if (strOld == ""
- || nOldLen == 0)
- {
- return;
- }
- //源串为空,没法替换
- if (strReplace == "")
- {
- return;
- }
- //替换每一处
- while (true)
- {
- //寻找要替换的字符串位置
- nFoundPos = strReplace.find(strOld, nFindStartPos);
- if (nFoundPos == string::npos)
- {
- break;
- }
- //替换掉
- strReplace.replace(nFoundPos, nOldLen, strNew);
- //搜索起始位置下移
- nFindStartPos = nFoundPos + nNewLen;
- if (nFindStartPos >= strReplace.length())
- {
- break;
- }
- }
- }
- /******************************************************************************
- 分解Cookie字符串
- ******************************************************************************/
- int CHTTP::_ParseCookieStr(HTTP::SCookie & sCookie, string strCookie)
- {
- if (strCookie == "")
- {
- return HTTP::PARSE_COOKIE_STR_COOKIE_NULL;
- }
- strCookie += ";";
- //提取Cookie名
- sCookie.strName = _CutStr(strCookie, "", "=");
- sCookie.strValue = _CutStr(strCookie, "=", ";");
- sCookie.strPath = _CutStr(strCookie, ";path=", ";");
- sCookie.strDomain = _CutStr(strCookie, ";domain=", ";");
- if (sCookie.strName == "")
- {
- return HTTP::PARSE_COOKIE_STR_NAME_NULL;
- }
- return 0;
- }
- /******************************************************************************
- 查找Cookie项是否已经存在Cookies表中
- ******************************************************************************/
- int CHTTP::_FindCookie(HTTP::SCookie const & sCookie)
- {
- int nListLen = (int)m_listCookies.size();
- int nFindList = 0;
-
- for (nFindList = 0; nFindList < nListLen; nFindList++)
- {
- HTTP::SCookie const & sFindCookie = m_listCookies[nFindList];
- if (sCookie.strName == sFindCookie.strName)
- {
- break;
- }
- }
- if (nFindList < nListLen)
- {
- return nFindList;
- }
- return -1;
- }
- /******************************************************************************
- 添加一个Cookie项
- ******************************************************************************/
- int CHTTP::_AddCookie(HTTP::SCookie const & sCookie)
- {
- if (sCookie.strName == "")
- {
- return HTTP::ADD_COOKIE_SCOOKIE_NAME_NULL;
- }
- int nFindCookie = _FindCookie(sCookie);
- //找到,替换掉
- if (nFindCookie > -1)
- {
- if (nFindCookie >= (int)m_listCookies.size())
- {
- return HTTP::ADD_COOKIE_SOCKET_FIND_INVALID;
- }
- HTTP::SCookie & sFindCookie = m_listCookies[nFindCookie];
- sFindCookie.strName = sCookie.strName;
- if (sCookie.strValue != "")
- {
- sFindCookie.strValue = sCookie.strValue;
- }
- if (sCookie.strPath != "")
- {
- sFindCookie.strPath = sCookie.strPath;
- }
- if (sCookie.strDomain != "")
- {
- sFindCookie.strDomain = sCookie.strDomain;
- }
- }
- //找不到,直接添加
- else
- {
- m_listCookies.push_back(sCookie);
- }
- return 0;
- }
- /******************************************************************************
- 分割字符串
- ******************************************************************************/
- void CHTTP::_SplitStr(vector<string> & listStr, string strSrc, string strSplit)
- {
- listStr.clear();
- if (strSrc == "")
- {
- return;
- }
- if (strSplit == "")
- {
- return;
- }
- string::size_type nStartPos = 0;
- while (true)
- {
- //寻找分割字符串
- if (nStartPos >= strSrc.length())
- {
- break;
- }
- string::size_type nSplitPos = strSrc.find(strSplit, nStartPos);
- if (nSplitPos == string::npos)
- {
- //找不到,则定位到字符串最后去
- nSplitPos = strSrc.length();
- }
- //截取字符串
- string strCut = strSrc.substr(nStartPos, nSplitPos - nStartPos);
- nStartPos = nSplitPos + strlen(strSplit.c_str());
- //添加到列表
- if (strCut != "")
- {
- listStr.push_back(strCut);
- }
- }
- }
- /******************************************************************************
- 小写字符串
- ******************************************************************************/
- void CHTTP::_ToLower(string & strLower)
- {
- if (strLower == "")
- {
- return;
- }
- transform(strLower.begin(), strLower.end()
- , strLower.begin(), tolower);
- }
- /******************************************************************************
- 启动并创建套接字
- ******************************************************************************/
- int CHTTP::_StartupCreateSocket(void)
- {
- m_bStartup = true;
- m_socket = INVALID_SOCKET;
- //启动套接字
- WSADATA wsaData;
- if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
- {
- m_bStartup = false;
- return HTTP::STARTUP_CREATE_SOCKET_STARTUP;
- }
- //创建套接字
- m_socket = socket(AF_INET, SOCK_STREAM, 0);
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::STARTUP_CREATE_SOCKET_SOCKET;
- }
- return 0;
- }
- /**************************************************************************
- 填写地址信息
- **************************************************************************/
- int CHTTP::_FillAddrInfo(sockaddr_in & addr)
- {
- //获得域名的IP数据
- if (m_strDomain == "")
- {
- return HTTP::FILL_ADDR_INFO_DOMAIN_NULL;
- }
- ULONG ulIPData = 0;
- int nGetIPData = m_mapDNS.GetIPData(ulIPData, m_strDomain);
- if (nGetIPData != 0)
- {
- return nGetIPData;
- }
- if (ulIPData == 0)
- {
- return HTTP::FILL_ADDR_INFO_IP_ZERO;
- }
- //填写SOCKET地址信息
- if (m_nPort <= 0)
- {
- return HTTP::FILL_ADDR_INFO_PORT_INVALID;
- }
- addr.sin_family = AF_INET;
- addr.sin_addr.S_un.S_addr = ulIPData;
- addr.sin_port = htons(m_nPort);
- return 0;
- }
- /******************************************************************************
- 带超时的连接
- ******************************************************************************/
- int CHTTP::_ConnWithTimeout(sockaddr_in const & addr)
- {
- //以非阻塞模式,设置连接超时
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::CONN_WITH_TIMEOUT_INVALID_SOCKET;
- }
- ULONG arg = !0;
- if (ioctlsocket(m_socket, FIONBIO, &arg) != 0)
- {
- return HTTP::CONN_WITH_TIMEOUT_SETNB_FAIL;
- }
- //连接服务器
- if (addr.sin_addr.S_un.S_addr == 0
- || addr.sin_port <= 0)
- {
- return HTTP::CONN_WITH_TIMEOUT_ADDR_INVALID;
- }
- if (connect(m_socket, (sockaddr *)&addr, sizeof(addr)) != SOCKET_ERROR)
- {
- return HTTP::CONN_WITH_TIMEOUT_CONN_FAIL;
- }
- //实现连接超时
- int nSelectTimeout = _SelectTimeout();
- if (nSelectTimeout != 0)
- {
- return nSelectTimeout;
- }
- //恢复阻塞模式
- arg = 0;
- if (ioctlsocket(m_socket, FIONBIO, &arg) != 0)
- {
- return HTTP::CONN_WITH_TIMEOUT_SETB_FAIL;
- }
- return 0;
- }
- /******************************************************************************
- 使用select实现超时
- ******************************************************************************/
- int CHTTP::_SelectTimeout(void)
- {
- //用select实现连接超时
- if (m_nConnTimeout <= 0)
- {
- return HTTP::SELECT_TIMEOUT_TIMEOUT_INVALID;
- }
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::SELECT_TIMEOUT_INVALID_SOCKET;
- }
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(m_socket, &fds);
- timeval timeout;
- timeout.tv_sec = m_nConnTimeout / 1000;
- timeout.tv_usec = m_nConnTimeout % 1000;
- if (select(0, 0, &fds, 0, &timeout) <= 0)
- {
- //连接不上,重新从DNS获取IP,因为可能是因为DNS更新IP导致连接不上的
- int nClearDNS = m_mapDNS.ClearDNS();
- if (nClearDNS != 0)
- {
- return nClearDNS;
- }
- return HTTP::SELECT_TIMEOUT_CONN_TIMEOUT;
- }
- return 0;
- }
- /******************************************************************************
- 设置套接字的超时
- ******************************************************************************/
- int CHTTP::_SetSocketTimeout(void)
- {
- if (m_socket == INVALID_SOCKET)
- {
- return HTTP::SET_SOCKET_TIMEOUT_INVALID_SOCKET;
- }
- if (m_nSendTimeout <= 0
- || m_nRecvTimeout <= 0)
- {
- return HTTP::SET_SOCKET_TIMEOUT_VALUE_INVALID;
- }
- //设置发送超时
- DWORD dwSendTimeout = (DWORD)m_nSendTimeout;
- if (setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO
- , (char *)&dwSendTimeout, sizeof(dwSendTimeout)) != 0)
- {
- return HTTP::SET_SOCKET_TIMEOUT_SET_SND_TIMEOUT;
- }
- //设置接收超时
- DWORD dwRecvTimeout = (DWORD)m_nRecvTimeout;
- if (setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO
- , (char *)&dwRecvTimeout, sizeof(dwRecvTimeout)) != 0)
- {
- return HTTP::SET_SOCKET_TIMEOUT_SET_RCV_TIMEOUT;
- }
- return 0;
- }
|