www.pudn.com > NetPaw.rar > HttpResponseHdr.cpp
#include "StdAfx.h"
#include ".\httpresponsehdr.h"
CHttpResponseHdr::CHttpResponseHdr(void)
: m_pcResponse(NULL)
, m_nHeaderSize(0)
{
}
CHttpResponseHdr::~CHttpResponseHdr(void)
{
if( m_pcResponse )
{
delete m_pcResponse;
}
}
long CHttpResponseHdr::GetField(LPCTSTR szSession, LPTSTR pszValue, long nBuffSize)
{
if( !m_pcResponse || !szSession || !pszValue )
return -1;
long nPos, nDigits = -1;
CString sResponse = m_pcResponse;
nPos = sResponse.Find(szSession);
if(nPos != -1)
{
nPos += (long)_tcslen(szSession);
nPos += 2;
nDigits = sResponse.Find("\r\n", nPos) - nPos;
if( nDigits > 0 )
{
CString strValue = sResponse.Mid(nPos, nDigits);
if( nDigits < nBuffSize - 1 )
{
_tcscpy(pszValue, (LPCTSTR)strValue);
}
else
{
nDigits = -1;
}
}
}
return nDigits;
}
void CHttpResponseHdr::ParseHeader(char *pData, long nLength)
{
m_nHeaderSize = 0;
for( long i = 3; i < nLength; i++ )
{
if( (pData[i-3] == '\r') && (pData[i-2] == '\n')
&& (pData[i-1] == '\r') && (pData[i] == '\n') )
{
m_nHeaderSize = i + 1;
break;
}
}
if( m_nHeaderSize > 0 )
{
if( m_pcResponse )
delete m_pcResponse;
m_pcResponse = new char[m_nHeaderSize+1];
memcpy(m_pcResponse, pData, m_nHeaderSize);
m_pcResponse[m_nHeaderSize] = 0;
}
}
LONGLONG CHttpResponseHdr::GetDataLength()
{
LONGLONG nLength = -1;
char szValue[32];
if( GetField("Content-Length", szValue, sizeof(szValue)) != -1 )
{
nLength = _atoi64(szValue);
}
return nLength;
}
/* status code definition
_T("HTTP/1.0 200 OK\r\n");
_T("HTTP/1.0 201 Created\r\n");
_T("HTTP/1.0 202 Accepted\r\n");
_T("HTTP/1.0 204 No Content\r\n");
_T("HTTP/1.0 300 Multiple Choices\r\n");
_T("HTTP/1.0 301 Moved Permanently\r\n");
_T("HTTP/1.0 302 Moved Temporarily\r\n");
_T("HTTP/1.0 304 Not Modified\r\n");
_T("HTTP/1.0 400 Bad Request\r\n");
_T("HTTP/1.0 401 Unauthorized\r\n");
_T("HTTP/1.0 403 Forbidden\r\n");
_T("HTTP/1.0 404 Not Found\r\n");
_T("HTTP/1.0 500 Internal Server Error\r\n");
_T("HTTP/1.0 501 Not Implemented\r\n");
_T("HTTP/1.0 502 Bad Gateway\r\n");
_T("HTTP/1.0 503 Service Unavailable\r\n");
*/
int CHttpResponseHdr::GetStatusCode(void)
{
int nStatusCode = -1;
CString sFirstLine, sCode;
if( GetFirstLine(sFirstLine) )
{
int nIndex = sFirstLine.Find("HTTP/");
if( nIndex != -1 )
{
sCode = sFirstLine.Mid(nIndex + 9, 3);
// parse status code
nStatusCode = atoi((LPCTSTR)sCode);
}
}
return nStatusCode;
}
BOOL CHttpResponseHdr::GetFirstLine(CString& sLine)
{
BOOL bResult = FALSE;
CString sHeader = m_pcResponse;
if( !sHeader.IsEmpty() )
{
int nIndex = sHeader.Find("\r\n");
if( nIndex != -1 )
{
sLine = sHeader.Left(nIndex);
bResult = TRUE;
}
}
return bResult;
}