虽然tc_http.h中包含了:
#include "util/tc_autoptr.h"
#include "util/tc_thread.h"
#include "util/tc_timeout_queue.h"
但并没有用到, 先忽略。
TC_URL是对url的管理, 从getDefaultPort中可以看出协议的默认端口:
string TC_URL::getDefaultPort() const
{
switch(_iURLType)
{
case HTTP:
return "80";
case HTTPS:
return "443";
case FTP:
return "21";
}
return "80";
}
如下是拼成一个url:
string TC_URL::toURL()
{
_sURL.clear();
_sURL = _sScheme;
_sURL += "://";
if(!_sUser.empty())
_sURL += _sUser;
if(!_sUser.empty() && !_sPass.empty())
{
_sURL += ":";
_sURL += _sPass;
}
if(!_sUser.empty())
_sURL += "@";
_sURL += _sDomain;
if(!isDefaultPort())
{
_sURL += ":";
_sURL += _sPort;
}
_sURL += getRequest();
return _sURL;
}
string TC_URL::getRequest() const
{
string sURL;
if(!_sPath.empty())
sURL += _sPath;
if(!_sQuery.empty())
sURL += "?" + _sQuery;
if(!_sRef.empty())
sURL += "#" + _sRef;
return sURL;
}
parseURL是解析url, 把各种字段解析出来, 简单。
随后的TC_Http和TC_HttpCookie管理整个http的buffer, 各种字符串操作, 仅此而已。 所以,以后不要自己写这些东西了。
随后的TC_HttpRequest和TC_HttpResponse都比较简单, 无非就是http中元素和操作的封装, 最重要的操作是:
int TC_HttpRequest::doRequest(TC_HttpResponse &stHttpRsp, int iTimeout)
{
//只支持短连接模式
setConnection("close");
string sSendBuffer = encode();
string sHost;
uint32_t iPort;
getHostPort(sHost, iPort);
TC_TCPClient tcpClient;
tcpClient.init(sHost, iPort, iTimeout);
int iRet = tcpClient.send(sSendBuffer.c_str(), sSendBuffer.length());
if(iRet != TC_ClientSocket::EM_SUCCESS)
{
return iRet;
}
stHttpRsp.reset();
string sBuffer;
char *sTmpBuffer = new char[10240];
size_t iRecvLen = 10240;
while(true)
{
iRecvLen = 10240;
iRet = tcpClient.recv(sTmpBuffer, iRecvLen);
if(iRet == TC_ClientSocket::EM_SUCCESS)
sBuffer.append(sTmpBuffer, iRecvLen);
switch(iRet)
{
case TC_ClientSocket::EM_SUCCESS:
if(stHttpRsp.incrementDecode(sBuffer))
{
delete []sTmpBuffer;
return TC_ClientSocket::EM_SUCCESS;
}
continue;
case TC_ClientSocket::EM_CLOSE:
delete []sTmpBuffer;
stHttpRsp.incrementDecode(sBuffer);
return TC_ClientSocket::EM_SUCCESS;
default:
delete []sTmpBuffer;
return iRet;
}
}
assert(true);
return 0;
}
对tcp socket进行了封装, easy.
不多说, 以后要用http相关接口, 直接去源码中找, 基本都有。