#endif
#include "stdafx.h"
#include "HttpLite.h"
#include
#include
#include
#include
HttpLite::HttpLite( void )
{
m_PageEncoding = ENCODE_UTF8;
m_RecordCookie = FALSE;
m_AllowAutoRedirect = TRUE;
m_AllowGzip = FALSE;
m_JustRquest = FALSE;
m_HttpHeader.SetAt("Accept", "*/*");
m_HttpHeader.SetAt("Accept-Language", "zh-cn");
//m_HttpHeader.SetAt("Accept-Encoding", "gzip, deflate");
m_HttpHeader.SetAt("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) HttpLite/Alvin4u");
m_HttpHeader.SetAt("Connection", "Keep-Alive");
m_HttpHeader.SetAt("Pragma", "no-cache");
//m_HttpHeader.SetAt("Cache-Control", "no-cache");
m_nPort = INTERNET_DEFAULT_HTTP_PORT;
m_intSession = new CInternetSession(_T("HttpLiteSession"),
0,
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
INTERNET_FLAG_DONT_CACHE);
m_intSession->SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3); //1次重试
m_intSession->SetOption(INTERNET_OPTION_CONNECT_BACKOFF,500);
}
HttpLite::~HttpLite(void)
{
if (m_intSession!=NULL)
{
m_intSession->Close();
delete m_intSession;
m_intSession = NULL;
}
}
void HttpLite::SetTimeout( DWORD mills )
{
if (m_intSession!=NULL)
{
m_intSession->SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, mills); //连接超时
m_intSession->SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, mills); //接收超时
}
}
// DWORD HttpLite::Get( const CString sUrl, vector
// {
// CHttpFile * pFile = NULL;
// DWORD dwRst = 200;
//
// CString sRedirectUrl;
//
// m_HttpHeader.SetAt("Content-Type", "");
// CString headerRaw = getHeaderRaw();
// DWORD dwFlags = INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_DONT_CACHE;
// if (m_RecordCookie)
// dwFlags = dwFlags|INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_AUTO_REDIRECT;
//
// if (!m_RecordCookie && !m_AllowAutoRedirect)
// {
// dwFlags = dwFlags|INTERNET_FLAG_NO_AUTO_REDIRECT;
// m_AllowAutoRedirect = TRUE;
// }
//
// try
// {
// pFile = (CHttpFile*)m_intSession->OpenURL(sUrl,
// 1,
// dwFlags,
// headerRaw,
// headerRaw.GetLength());
// if (pFile == NULL)
// {
// dwRst = 500;
// goto endGet;
// }
//
// dwRst = progressResp(pFile, vctByte, sRedirectUrl);
// if (dwRst== NEED_REDIRECT || dwRst == 500)
// goto endGet;
// }
// catch(...)
// {
// dwRst = 500;
// goto endGet;
// }
//
// endGet:
// m_HttpHeader.SetAt("Cookie", "");
// m_HttpHeader.SetAt("Referer", "");
//
// if (pFile!=NULL)
// {
// pFile->Close();
// delete pFile;
// pFile = NULL;
// }
// if (dwRst == NEED_REDIRECT)
// {
// return Get(sRedirectUrl, vctByte);
// }
// return dwRst;
// }
DWORD HttpLite::HttpExecute( int httpMethod, vector
{
CHttpConnection *pHttp = NULL;
CHttpFile *pFile = NULL;
DWORD type = 0,dwRst = 500;
CString sRedirectUrl;
if(!AfxParseURL(sUrl,type,m_strServerName,m_strQueryString,m_nPort)){
return 500;
}
try{
//STEP.1.设置FLAGS
DWORD dwFlags = INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_DONT_CACHE;
if(type == AFX_INET_SERVICE_HTTPS) //https方式 AFX_INET_SERVICE_HTTPS=4107
dwFlags = dwFlags | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
if (m_RecordCookie || !m_AllowAutoRedirect)
{
dwFlags = dwFlags | INTERNET_FLAG_NO_AUTO_REDIRECT;
if (m_RecordCookie)
dwFlags = dwFlags | INTERNET_FLAG_NO_COOKIES;
}
//STEP.2.设置Cookie
CString selfCookie;
m_HttpHeader.Lookup(_T("Cookie"), selfCookie);
if (m_RecordCookie)
{//手动处理Cookie
if (!selfCookie.IsEmpty())
m_respCookieRaw += selfCookie;
m_HttpHeader.SetAt(_T("Cookie"), m_respCookieRaw);
}else{
if (!selfCookie.IsEmpty())
handleCookie(sUrl, selfCookie);
m_HttpHeader.SetAt(_T("Cookie"), _T(""));
}
//STEP.3.设置CONTENT-TYPE
if (httpMethod == HTTP_POST)
{
if (pd!=NULL && !pd->m_ContentType.IsEmpty())
{
m_HttpHeader.SetAt(_T("Content-Type"), pd->m_ContentType);
}else{
CString contentType;
m_HttpHeader.Lookup(_T("Content-Type"), contentType);
if (contentType.IsEmpty())
m_HttpHeader.SetAt(_T("Content-Type"), _T("application/x-www-form-urlencoded"));
}
}else{
m_HttpHeader.SetAt(_T("Content-Type"), _T(""));
}
//STEP.4.打开连接
pHttp = m_intSession->GetHttpConnection((LPCTSTR)m_strServerName,m_nPort);
if (pHttp == NULL)
goto endHttpExecute;
pFile = pHttp->OpenRequest(httpMethod==HTTP_GET?CHttpConnection::HTTP_VERB_GET:CHttpConnection::HTTP_VERB_POST,(LPCTSTR)m_strQueryString,NULL,1,NULL,NULL,dwFlags);
if(pFile==NULL)
goto endHttpExecute;
CString headerRaw = getHeaderRaw();
//STEP.5.发送数据
if (httpMethod == HTTP_POST)
{
if (pd == NULL ||
(pd->m_EntityType==pd->NVP_ENTITY && pd->nvps.IsEmpty()) ||
(pd->m_EntityType==pd->TEXT_ENTITY && pd->m_RawText.IsEmpty()))
{
if(pFile->SendRequest(headerRaw, headerRaw.GetLength())==FALSE){
goto endHttpExecute;
}
}else{
BOOL sendRst = FALSE;
if (pd->m_EntityType==pd->NVP_ENTITY)
{
CString pdStr = pd->NvpToString(m_PageEncoding);
sendRst = pFile->SendRequest(headerRaw, pdStr.GetBuffer(0), pdStr.GetLength());
pdStr.ReleaseBuffer();
}else{
char * szText = Encode::ConvertSet2UTF8((LPCTSTR)pd->m_RawText, m_PageEncoding);
sendRst = pFile->SendRequest(headerRaw, szText, strlen(szText));
delete [] szText;
}
if (!sendRst)
goto endHttpExecute;
}
}else{
if(pFile->SendRequest(headerRaw, NULL, 0)==FALSE){
goto endHttpExecute;
}
}
//STEP.6.处理返回数据
dwRst = progressResp(pFile, respByteVct, sRedirectUrl);
//if (dwRst== NEED_REDIRECT || dwRst == 500)
// goto endHttpExecute;
// }catch(CInternetException &e){
// TCHAR tzErrMsg[MAX_PATH] = {0};
// e.GetErrorMessage(tzErrMsg,sizeof(tzErrMsg));
// }catch(CException & e){
// TCHAR tzErrMsg[MAX_PATH] = {0};
// e.GetErrorMessage(tzErrMsg,sizeof(tzErrMsg));
// }catch(exception & e){
// e.what();
}catch(...){
dwRst = 500;
}
endHttpExecute:
m_HttpHeader.SetAt("Cookie", "");
m_HttpHeader.SetAt("Referer", "");
m_HttpHeader.SetAt("Content-Type", "");
if (pFile!=NULL)
{
pFile->Close();
delete pFile;
pFile = NULL;
}
if (pHttp!=NULL)
{
pHttp->Close();
delete pHttp;
pHttp = NULL;
}
if (dwRst == NEED_REDIRECT)
{
respByteVct.clear();
return HttpExecute(HTTP_GET, respByteVct, sRedirectUrl, NULL);
}
return dwRst;
}
CString HttpLite::getHeaderRaw()
{
CString key,val,raw;
POSITION pos = m_HttpHeader.GetStartPosition();
while(pos){
m_HttpHeader.GetNextAssoc(pos, key, val);
if (val.IsEmpty())
continue;
raw += (key + _T(": ") + val + _T("\r\n"));
}
raw.Delete(raw.GetLength()-2, 2);
return raw;
}
void HttpLite::getRespBody( CHttpFile * pFile, vector
{
byte buf[1024];
ZeroMemory(buf, 1024);
try{
DWORD len = 0;
while((len=pFile->GetLength())>0)
{
UINT count = pFile->Read(buf, len<1024?len:1024);
for(UINT i = 0; i < count; ++i){
vecByte.push_back(buf[i]);
}
ZeroMemory(buf, 1024);
}
// while((count = pFile->Read(buf,1024))>0){
// len = pFile->GetLength();
// for(UINT i = 0; i < count; ++i){
// vecByte.push_back(buf[i]);
// }
// if( count <= 0 )
// break;
// }
}catch(...){
}
}
DWORD HttpLite::progressResp( CHttpFile * pFile , vector
{
DWORD dwStatuCode = 0;
pFile->QueryInfoStatusCode(dwStatuCode);
if (dwStatuCode<200 || dwStatuCode>403){
if (dwStatuCode == 404)
return NO_PAGE;
else
return 500;
}
pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, m_respHeaderRaw);
if (m_RecordCookie)
{
recordCookie();
if (dwStatuCode>299 && dwStatuCode<400 && m_AllowAutoRedirect)
{
sRerictUrl = GetRespItem("Location");
//sRerictUrl.Trim();
if (!sRerictUrl.IsEmpty())
{
CString url = pFile->GetFileURL();
if (sRerictUrl.Find('/')==0) //以/开头的
{
int endIdx = url.Find('/', 7);
if (endIdx==-1)
sRerictUrl = url + sRerictUrl;
else
sRerictUrl = url.Mid(0, endIdx) + sRerictUrl;
}
else if(sRerictUrl.Find("./")==0)
{
sRerictUrl = url.Mid(0, url.ReverseFind('/')) + sRerictUrl.Mid(1, sRerictUrl.GetLength()-1);
}
else if (sRerictUrl.Find("http://")==-1)
{
sRerictUrl = url.Mid(0, url.ReverseFind('/')+1) + sRerictUrl;
}
else if (sRerictUrl.Find("../") == 0)
{
url = url.Mid(0, url.ReverseFind('/'));
sRerictUrl = url.Mid(0, url.ReverseFind('/')) + sRerictUrl.Mid(2, sRerictUrl.GetLength()-2);
}else if(sRerictUrl.Find("http://")==0){
}else{
sRerictUrl = url + sRerictUrl;
}
return NEED_REDIRECT;
}
}
}
if (!m_AllowAutoRedirect)
m_AllowAutoRedirect = TRUE;
if (!m_JustRquest) //如果只是请求就不获取返回的数据
getRespBody(pFile, vecByte);
if(GetRespItem(_T("Content-Encoding")).Find(_T("gzip"))>-1)
return NEED_UNGZIP;
else
return 200;
}
DWORD HttpLite::GetPage( const CString sUrl, CString & pageSrc )
{
DWORD dwRst = 200;
vector
//dwRst = Get(sUrl, vctByte);
dwRst = HttpExecute(HTTP_GET, vctByte, sUrl);
vctByte2String(pageSrc, vctByte, dwRst==NEED_UNGZIP?TRUE:FALSE);
return dwRst;
}
DWORD HttpLite::GetFile( const CString sUrl, CString savePath )
{
DWORD dwRst = 200;
vector
//dwRst = Get(sUrl, vctByte);
dwRst = HttpExecute(HTTP_GET, vctByte, sUrl);
//ifstream(strFileName.GetString(), std::ios_base::binary)
int len = vctByte.size();
if (len==0)
return dwRst;
char * data = (char*)alloca(len);
ZeroMemory(data, len);
copy(vctByte.begin(),vctByte.end(),data);
//locale loc = locale::global(locale(""));//要打开的文件路径含中文,设置全局locale为本地环境
setlocale(LC_ALL,"Chinese-simplified");//设置中文环境
std::ofstream os((LPCTSTR)savePath, std::ios_base::binary);
//locale::global(loc);//恢复全局locale
setlocale(LC_ALL,"C");//设置中文环境
while(len>0){
os.write(data, len>1024?1024:len);
data+=1024;
len-=1024;
}
os.close();
return dwRst;
}
DWORD HttpLite::Post( const CString sUrl, PostData & pd, CString & sRecvData )
{
DWORD dwRst = 500;
vector
dwRst = HttpExecute(HTTP_POST, vctByte, sUrl, &pd);
vctByte2String(sRecvData, vctByte, dwRst==NEED_UNGZIP?TRUE:FALSE);
return dwRst;
}
DWORD HttpLite::Post( const CString sUrl, vector
{
PostData _pd;
for(int i=0,len = pd.size(); i
_pd.Put(pd[i].first.c_str(), CString(pd[i].second.c_str()));
}
DWORD dwRst = 500;
vector
dwRst = HttpExecute(HTTP_POST, vctByte, sUrl, &_pd);
vctByte2String(sRecvData, vctByte, dwRst==NEED_UNGZIP?TRUE:FALSE);
return dwRst;
}
void HttpLite::recordCookie()
{
m_HttpHeader.SetAt("Cookie", "");
CString respCookie = GetRespItem("Set-Cookie");
if (respCookie.IsEmpty())
return;
CString tmp,keyName;
int endIdx = 0;
int cutIdx,cutCount = 0;
while(TRUE){
endIdx = respCookie.Find("\r\n");
if (endIdx>-1)
tmp = respCookie.Mid(0, endIdx);
else
tmp = respCookie;
endIdx = tmp.Find(';');
if (endIdx>-1)
tmp = tmp.Mid(0, tmp.Find(';')+1);
else
tmp = tmp + ';';
keyName = tmp.Mid(0, tmp.Find('=')+1);
//删除掉重复的cookie
cutIdx = m_respCookieRaw.Find(keyName);
if (cutIdx!=-1)
{
cutCount = m_respCookieRaw.Find(';', cutIdx)-cutIdx+1;
if (cutCount>0)
m_respCookieRaw.Delete(cutIdx, cutCount);
}
m_respCookieRaw = m_respCookieRaw + tmp;
// if (m_strRespCookie.Find(tmp)==-1){
// m_strRespCookie = m_strRespCookie + tmp;
// }
endIdx = respCookie.Find("\r\n");
if (endIdx<=0){
break;
}
respCookie = respCookie.Mid(endIdx+2);
}
}
CString HttpLite::GetRespItem(CString itemName )
{
if(m_respHeaderRaw.IsEmpty()){
return "";
}
CString sHeaderRaw = m_respHeaderRaw;
sHeaderRaw.MakeLower();
itemName.MakeLower();
CString rst = "";
int startIdx = sHeaderRaw.Find(itemName);
int endIdx = -1;
CString strLine,item;
while(startIdx!=-1){
endIdx = m_respHeaderRaw.Find("\r\n", startIdx);
strLine = m_respHeaderRaw.Mid(startIdx, endIdx-startIdx);
item = strLine.Mid(itemName.GetLength()+1);
//item.Trim();
item.TrimLeft();
item.TrimRight();
rst = (rst.IsEmpty()?"":rst+"\r\n") + item;
startIdx = sHeaderRaw.Find(itemName, endIdx+2);
}
return rst;
}
BOOL HttpLite::vctByte2String( CString & resp, vector
{
char * pBuf = NULL;
int len = vctByte.size();
if (len>0)
{
pBuf = (char*)alloca(len+1);
if (pBuf==NULL)
return FALSE;
ZeroMemory(pBuf, len+1);
copy(vctByte.begin(), vctByte.end(), pBuf);
//if (!needUnZip)
// resp.Format("%s", pBuf);
char * dest = Encode::ConvertSet2GBK(pBuf, m_PageEncoding==ENCODE_UTF8?CP_UTF8:CP_ACP);
resp.Format("%s", dest);
if (m_PageEncoding==ENCODE_UTF8)
{
delete [] dest;
}
}
return TRUE;
}
BOOL HttpLite::GetCookie( CString url, CString cookieName, CString &cookieValue )
{
if (m_RecordCookie)
{
int startIdx = m_respCookieRaw.Find(cookieName);
if (startIdx == -1)
return FALSE;
else
startIdx = startIdx + cookieName.GetLength()+1;
cookieValue = m_respCookieRaw.Mid(startIdx, m_respCookieRaw.Find(';', startIdx)-startIdx);
return TRUE;
}else{
return m_intSession->GetCookie(url, cookieName, cookieValue);
}
}
void HttpLite::GetCookieRaw( CString & cookieRaw )
{
cookieRaw.Format("%s", m_respCookieRaw);
}
void HttpLite::SetCookie( CString url, CString cookieStr )
{
m_HttpHeader.SetAt(_T("Cookie"), cookieStr);
}
void HttpLite::handleCookie( const CString & url, CString & cookieStr )
{
cookieStr.TrimRight();
int indexA;
int indexE;
while(TRUE){
indexA = cookieStr.Find(';');
indexE = cookieStr.Find('=');
if(indexE>-1){
m_intSession->SetCookie(url, cookieStr.Left(indexE), cookieStr.Mid(indexE+1, indexA==-1?(cookieStr.GetLength()-indexE):(indexA-indexE-1)));
}
if(indexA==-1){
break;
}else{
cookieStr = cookieStr.Mid(indexA+1);
cookieStr.TrimLeft();
}
}
}
#define IsHexNum(c) ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
WCHAR* Encode::CharToWchar( const char* str, int CP_CODE /*= CP_UTF8*/ )
{
int len = MultiByteToWideChar(CP_CODE, 0, str, -1, NULL, 0);
WCHAR* result = new WCHAR[len];
MultiByteToWideChar(CP_CODE, 0, str, -1, result, len);
return result;
}
char* Encode::WcharToChar( WCHAR* str, int CP_CODE /*= CP_UTF8*/ )
{
int len = WideCharToMultiByte(CP_CODE, 0, str, -1, NULL, 0, NULL, NULL);
char *result = new char[len];
WideCharToMultiByte(CP_CODE, 0, str, -1, result, len, NULL, NULL);
return result;
}
char * Encode::ConvertSet2GBK( const char * str, int ENCODE /*= CP_UTF8*/ )
{
if (ENCODE == CP_ACP)
return (char*)str;
WCHAR * wChar = CharToWchar(str, CP_UTF8);
char * aChar = WcharToChar(wChar, CP_ACP);
delete [] wChar;
return aChar;
}
char * Encode::ConvertSet2UTF8( const char * str, int ENCODE /*= CP_UTF8*/ )
{
if (ENCODE == CP_ACP)
return (char*)str;
WCHAR * wChar = CharToWchar(str, CP_ACP);
char * aChar = WcharToChar(wChar, CP_UTF8);
delete [] wChar;
return aChar;
}
std::string Encode::UrlEncode( CString & text, int encoding /*= ENCODE_UTF8*/)
{
static char hex[] = "0123456789ABCDEF";
string dst;
char *m_lpSrc = ConvertSet2UTF8((LPCTSTR)text, encoding == ENCODE_UTF8?CP_UTF8:CP_ACP);
int m_nSrcLen = strlen(m_lpSrc);
for (int i = 0; i < m_nSrcLen; i++){
unsigned char ch = m_lpSrc[i];
if(isalnum(ch) || ch=='.' || ch=='_' || ch=='-' || ch=='*' || ch=='(' || ch==')'){ // || (filtChar!=NULL && (filtChar == ch || ch == '='))
dst += ch;
}else if (isspace(ch)){
dst += '+';
}else{
unsigned char c = static_cast
dst += '%';
dst += hex[c / 16];
dst += hex[c % 16];
}
}
if (encoding == ENCODE_UTF8)
{
delete [] m_lpSrc;
}
m_lpSrc = NULL;
return dst;
}
std::string Encode::UrlDecode( CString & text, int encoding /*= ENCODE_UTF8*/ )
{
int length = text.GetLength(), i=0;
const char * m_lpSrc = (LPCTSTR)text;
char * buf = (char*)alloca(length);
ZeroMemory(buf, length);
LPSTR p = buf;
char ch[2];
while(i < length)
{
if(i <= length -3 && m_lpSrc[i] == '%' && isalnum(m_lpSrc[i+1]) && isalnum(m_lpSrc[i+2])) //IsHexNum
{
ch[0] = m_lpSrc[ i + 1];
ch[1] = m_lpSrc[ i + 2];
sscanf(ch, "%x", p++);
i += 3;
}
else if (m_lpSrc[i] == '+')
{
*(p++) = ' ';
i++;
}
else
{
*(p++) = m_lpSrc[i++];
}
}
char * dest = ConvertSet2GBK(buf, encoding == ENCODE_UTF8?CP_UTF8:CP_ACP);
string rst;
rst.append(dest);
if (encoding == ENCODE_UTF8)
delete [] dest;
return rst;
}
CString Encode::UnicodeEncode( CString & text )
{
#ifdef UNICODE
WCHAR * m_lpSrc = text.GetString();
int length = text.GetLength();
wstring rst;
#else
USES_CONVERSION;
WCHAR * m_lpSrc = A2W(text);
int length = wcslen(m_lpSrc);
string rst;
#endif
WCHAR ch;
TCHAR tmp[5];
ZeroMemory(tmp, 5);
for(int i=0;i
ch = m_lpSrc[i];
if (ch>0xff) //如果为中文
{
sprintf(tmp, "%x", ch);
rst.append("\\u");
rst.append(tmp);
}else{
if (isalnum(ch)) //如果为英文或数字
{
//rst.push_back(ch);
rst += ch;
}else{
sprintf(tmp, _T("%04x"), ch);
rst.append(_T("\\u"));
rst.append(tmp);
}
}
}
return rst.c_str();
}
CString Encode::UnicodeDecode( CString & text )
{
int length = text.GetLength();
#ifdef UNICODE
string wrst;
USES_CONVERSION;
const WCHAR * m_lpSrc = W2A(text);
WCHAR ch;
#else
wstring wrst;
const char * m_lpSrc = text.GetString();
char ch;
#endif
bool escape = false;
int intHex;
TCHAR tmp[5];
ZeroMemory(tmp, 5);
for(int i=0; i
ch = m_lpSrc[i];
switch (ch)
{
case '\\':
case '%':
escape = true;
break;
case 'u':
case 'U':
if (escape)
{
memcpy(tmp, m_lpSrc+i+1, 4);
sscanf(tmp, _T("%x"), &intHex); //把16进制字符转换为数字
//wrst.push_back(intHex);
wrst += intHex;
i+=4;
escape=false;
}else{
//wrst.push_back(ch);
wrst += ch;
}
break;
default:
//wrst.push_back(ch);
wrst += ch;
break;
}
}
#ifdef UNICODE
return wrst.c_str();
#else
string rst;
USES_CONVERSION;
rst.append(W2A(wrst.c_str()));
return rst.c_str();
#endif
}
////////////////////////////// P O S T D A T A//////////////////////////////////////
PostData::PostData( const int type /*= NVP_ENTITY*/ )
{
m_EntityType = type;
m_PostDataNeedUrlEncode = TRUE;
}
void PostData::Put( const CString name, const CString &value )
{
nvps.AddTail(NVP(name, value));
}
void PostData::Remove( const CString &name )
{
NVP nvp(name, _T(""));
POSITION pos = nvps.Find(nvp);
while(pos){
nvps.RemoveAt(pos);
pos = nvps.Find(nvp);
}
}
CString PostData::GetPostValue( const CString &name )
{
NVP nvp(name, _T(""));
POSITION pos = nvps.Find(nvp);
if(pos){
nvp=nvps.GetAt(pos);
return nvp.value;
}else{
return CString("");
}
}
void PostData::Replace( const CString &name, const CString &value )
{
NVP nvp(name, value);
POSITION pos = nvps.Find(nvp);
if (pos)
{
while(pos){
nvps.SetAt(pos, nvp);
pos = nvps.Find(nvp, pos);
}
}
else
{
nvps.AddTail(nvp);
}
}
void PostData::SetNvpRaw( CString rawText, bool bReplace /*= false*/ )
{
BOOL flag = TRUE;
int indexA;
int indexE;
while(flag){
indexA = rawText.Find('&');
indexE = rawText.Find('=');
if(indexE>-1){
NVP item(rawText.Left(indexE), rawText.Mid(indexE+1, indexA==-1?(rawText.GetLength()-indexE):(indexA-indexE-1)));
if (bReplace)
{
POSITION pos = nvps.Find(item);
if (pos)
nvps.SetAt(pos, item);
else
nvps.AddTail(item);
}
else
nvps.AddTail(item);
}
if(indexA==-1){
flag = FALSE;
}else{
rawText = rawText.Mid(indexA+1);
}
}
}
void PostData::SetTextRaw( CString rawText )
{
this->m_RawText = rawText;
}
void PostData::ClearData()
{
m_RawText.Empty();
nvps.RemoveAll();
}
CString PostData::NvpToString( int enc /*= 0*/ )
{
if (nvps.IsEmpty())
return CString("");
LPNVP item;
int len = nvps.GetCount();
if (m_PostDataNeedUrlEncode==FALSE)
{
CString _rawText;
for (int i=0; i
item = &(NVP)nvps.GetAt(nvps.FindIndex(i));
_rawText += item->name + _T("=") + item->value + _T("&");
}
_rawText.Delete(_rawText.GetLength()-1, 1);
if (enc==0)
return _rawText;
int _enc = enc == Encode::ENCODE_GBK ? CP_ACP : CP_UTF8;
char * szText = Encode::ConvertSet2UTF8((LPCTSTR)_rawText, _enc);
CString strText(szText);
delete [] szText;
return strText;
}else{
if (enc == 0)
return CString("");
string _rawText;
int _enc = enc == Encode::ENCODE_GBK ? CP_ACP : CP_UTF8;
for (int i=0; i
item = &(NVP)nvps.GetAt(nvps.FindIndex(i));
char * szName = Encode::ConvertSet2UTF8((LPCTSTR)item->name, _enc);
_rawText.append(szName).append("=").append(Encode::UrlEncode(item->value, enc)).append("&");
delete [] szName;
}
_rawText.erase(_rawText.size()-1); //删除最后一位
return CString(_rawText.c_str());
}
}