示例#1
0
文件: KHttp.cpp 项目: korman/Temp
int KHttp::getHttpFileMemory(const KData& server, const KData& httpfile,
		char** ppKData)
{
	char* pKData = NULL;
	KData httpRequest = "GET ";
	httpRequest += httpfile;
	httpRequest += " HTTP/1.1";
	httpRequest += CRLF;
	httpRequest += "Host: ";
	httpRequest += server;
	httpRequest += CRLF;
	httpRequest += CRLF;
	unsigned char buff[MTU];
	KTcpClientSocket clientSock(server, 80);
	clientSock.connect();
	KConnection &conn = clientSock.getConn();
	string stringTmp = httpRequest.getData();
	conn.writeData(stringTmp);
	int iRead = 0;
	bool bFound = false;
	KData dtHead;
	int iLength = 0;
	int iWrite = 0;
	int m_iStatusCode = 0;
	bool bRun = true;
	while ((iRead = conn.readn(buff, MTU)) > 0 && bRun)
	{
		if (!bFound)
		{
			for (int i = 0; i < iRead - 4; i++)
			{
				if (buff[i] == 0x0d && buff[i + 1] == 0x0a
						&& buff[i + 2] == 0x0d && buff[i + 3] == 0x0a)
				{
					KData dtLine;
					dtHead = KData((char*) buff, i + 4);
					KData dtRequestLine, dtCode;

					if (NOT_FOUND == dtHead.match(CRLF, &dtRequestLine, false))
					{
						return -1;
					}
					if (NOT_FOUND == dtRequestLine.match("HTTP/1.1", NULL, true)
							&& NOT_FOUND
									== dtRequestLine.match("HTTP/1.0", NULL,
											true))
					{
						return -1;
					}
					if (NOT_FOUND == dtRequestLine.match(SP, NULL, true))
					{
						return -1;
					}
					if (NOT_FOUND == dtRequestLine.match(SP, &dtCode, true))
					{
						return -1;
					}
					if ((int) dtCode == 0 && (int) dtCode != 200)
					{
						return -1;
					}

					while (NOT_FOUND != dtHead.match(CRLF, &dtLine, true))
					{
						KData dtBefVal;
						if (FOUND == dtLine.match(":", &dtBefVal, true))
						{
							dtBefVal.removeSpaces();
							if (isEqualNoCase(dtBefVal, "Content-Length"))
							{
								dtLine.removeSpaces();
								iLength = (int) dtLine;
							}
						}
						else if (NOT_FOUND
								!= dtLine.match("HTTP/1.1", NULL, true))
						{
							dtLine.removeSpaces();
							dtLine.match(" ", &dtBefVal, true);
							m_iStatusCode = (int) dtBefVal;
						}

					}
					if (iLength <= 0)
					{
						return -1;
					}
					else if (m_iStatusCode != 200)
					{
						return -1;
					}
					else
					{
						pKData = new char[iLength];
					}

					memcpy(pKData, &buff[i + 4], iRead - i - 4);
					iWrite += (iRead - i - 4);
					bFound = true;

					if (iLength > 0 && iWrite == iLength)
					{
						bRun = false;
						break;
					}
				}
			}
		}
		else
		{
			memcpy(&pKData[iWrite], buff, iRead);
			iWrite += iRead;
			if (iWrite == iLength)
			{
				break;
			}
		}
	}

	conn.close();
	*ppKData = pKData;
	return iWrite;
}