方便自己用的c++ http类

#ifndef __HTTP_LITE_H__
#define __HTTP_LITE_H__
/**
* Http工具类 
* Author: Alvin4u
* Ver: 1.0.0.2
* Date: 20120703
*/


#include <afxinet.h>
#include <string>
#include <vector>
#include <iostream>
#include <Afxtempl.h>


using namespace std;


///NVP 名值对///
typedef struct _tagNVP{
CString name;
CString value;
_tagNVP(){}
_tagNVP(CString name, CString value){
this->name = name;
this->value = value;
}


_tagNVP(const CString &val,const TCHAR &sepret)
{
int pos=val.Find(sepret);
if (pos>-1)
{
this->name=val.Left(pos);
this->value=val.Mid(pos+1);
}
}


//重载copy构造函数
_tagNVP(const _tagNVP &n){
this->name = n.name;
this->value = n.value;
}


//重载比较
BOOL operator == (const _tagNVP &n) const
{
if(name.CompareNoCase(n.name)==0)
return TRUE;
else
return FALSE;
}


//重载赋值
_tagNVP& operator=(const _tagNVP &n){
this->name = n.name;
this->value = n.value;
return *this;
}

}NVP,* LPNVP;


class PostData{
public:
enum{
NVP_ENTITY = 1, //默认方式,普通键值对POST
TEXT_ENTITY = 2, //纯文本方式
};


BOOL m_PostDataNeedUrlEncode; //是否把PostData进行UrlEncode编码
int m_EntityType; //ENTITY_TYPE
CString m_ContentType;
CString m_RawText;


CList<NVP,NVP&> nvps; //要发布的nvp


public:
PostData(const int type = NVP_ENTITY);


void Put(const CString name, const CString &value); //往Nvp里加入名字对


void Remove(const CString &name); //删除项


CString GetPostValue(const CString &name); //取nvp的值


void Replace(const CString &name, const CString &value); //替换其中的项


void SetNvpRaw(CString rawText, bool bReplace = false); //把post字符转入


void SetTextRaw(CString rawText);


void ClearData(); //清除所有名值对或文件对


CString NvpToString(int enc = 0); //把NVP生成PostDataRaw
};


class HttpLite
{
public:
HttpLite(void);
virtual ~HttpLite(void);


enum {
ENCODE_UTF8 = 1, 
ENCODE_GBK = 2, 
HTTP_GET = 3, 
HTTP_POST = 4, 
HTTP_MUILT_POST = 5,
HTTP_SINGLE_FILE_POST = 6, //只上传一个文件的类型
NEED_UNGZIP = 103, 
NEED_REDIRECT = 302, 
NO_PAGE = 404
};


public:
int m_PageEncoding;
BOOL m_RecordCookie;
BOOL m_AllowAutoRedirect;
BOOL m_AllowGzip;
CString m_ContentType;
BOOL m_JustRquest; //是否只是访问,即不获取返回信息


CMap<CString, LPCTSTR, CString, LPCTSTR> m_HttpHeader;


// DWORD Get(const CString sUrl, vector<byte> & vctByte);


DWORD GetPage(const CString sUrl, CString & pageSrc);


DWORD GetFile(const CString sUrl, CString savePath);


DWORD Post(const CString sUrl, PostData & pd, CString & sRecvData);


DWORD Post(const CString sUrl, vector<pair<string, string>> & pd, CString & sRecvData);


DWORD HttpExecute(int Method, vector<byte> & respByteVct, const CString sUrl, PostData * pd = NULL);


CString GetRespItem(CString itemName);


void SetTimeout(DWORD mills);


BOOL GetCookie(CString url, CString cookieName, CString & cookieValue);


void SetCookie(CString url, CString cookieStr);


void GetCookieRaw(CString & cookieRaw);


private:
CInternetSession * m_intSession;


服务器参数/
INTERNET_PORT m_nPort;
CString m_strServerName;
CString m_strQueryString;
CString m_respCookieRaw;
CString m_respHeaderRaw;




void getRespBody(CHttpFile * pFile, vector<byte> & vecByte);


DWORD progressResp(CHttpFile * pFile , vector<byte> & vecByte, CString & sRerictUrl);


CString getHeaderRaw();


void recordCookie();


BOOL vctByte2String(CString & resp, vector<byte> & vctByte, BOOL needUnZip);


void handleCookie(const CString & url, CString & cookieStr);
};


class Encode
{
public:
enum {ENCODE_UTF8 = 1, ENCODE_GBK = 2};


static WCHAR* CharToWchar(const char* str, int CP_CODE = CP_UTF8);


static char* WcharToChar(WCHAR* str, int CP_CODE = CP_UTF8);


static char * ConvertSet2GBK(const char * str, int ENCODE = CP_UTF8);


static char * ConvertSet2UTF8(const char * str, int ENCODE = CP_UTF8);


static string UrlEncode(CString & text, int encoding = ENCODE_UTF8);


static string UrlDecode(CString & text, int encoding = ENCODE_UTF8);


static CString UnicodeEncode(CString & text);


static CString UnicodeDecode(CString & text);


};

#endif


#include "stdafx.h"
#include "HttpLite.h"
#include <fstream>
#include <ctype.h>
#include <MALLOC.H>
#include <atlconv.h>


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<byte> & vctByte )
// {
// 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<byte> & respByteVct, const CString sUrl, PostData * pd /*= NULL*/ )
{
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> & vecByte )
{
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<byte> & vecByte, CString & sRerictUrl)
{
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<byte> vctByte;


//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<byte> vctByte;


//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<byte> vctByte;
dwRst = HttpExecute(HTTP_POST, vctByte, sUrl, &pd);


vctByte2String(sRecvData, vctByte, dwRst==NEED_UNGZIP?TRUE:FALSE);


return dwRst;
}


DWORD HttpLite::Post( const CString sUrl, vector<pair<string, string>> & pd, CString & sRecvData )
{
PostData _pd;


for(int i=0,len = pd.size(); i<len; i++)
{
_pd.Put(pd[i].first.c_str(), CString(pd[i].second.c_str()));
}


DWORD dwRst = 500;
vector<byte> vctByte;
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<byte> & vctByte , BOOL needUnZip)
{
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<unsigned char>(ch);
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<length;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<length;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<len; 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<len; 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());
}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值