如何使用基于Linux的c ++模拟浏览器登录https网站?

时间:2015-03-29 01:52:00

标签: linux browser https simulate postdata

大家好,我的目标是使用基于Linux的C ++后台服务程序登录https网站并下载网页。   细节需求如下:   (1)连接到“https://www.space-track.org/auth/login”   (2)输入用户名和密码以便成功登录   (3)将一些formdata发布到本网站   (4)下载网页。

现在,我的方法是使用MFC :: CInternetSession(代码如下。它在MS-Windows中),但它不成功。代码中必定存在一些问题。我希望你能帮我解决问题。也许你可以用C ++来提出更好的解决方案来模拟基于Linux的浏览器。非常感谢你!

Url = "https://www.space-track.org/auth/login/";

nPort = INTERNET_DEFAULT_HTTP_PORT;
CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded");

if (AfxParseURL(Url,dwSeviceType,strServerName,strTarget,nPort) == 0)
    return false;

CInternetSession sess;

sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,1000*20);
sess.EnableStatusCallback(TRUE);

CHttpConnection* pHttpConnect = sess.GetHttpConnection(strServerName,nPort);

CHttpFile* pHttpFile = pHttpConnect->OpenRequest(CHttpConnection::HTTP_VERB_POST,
    strTarget,NULL,1,NULL,NULL,INTERNET_FLAG_SECURE);


 CString strUserName = "*****";
 CString strPassword = "*****";
 CString strUserinfo;
 strUserinfo.Format(_T("identity=%s&password=%s"),strUserName,strPassword);

try
{
    BOOL bResult =pHttpFile->SendRequest(strHeaders,(LPVOID)(LPCTSTR)strUserinfo,strUserinfo.GetLength()* sizeof(TCHAR));
    //BOOL bResult =pHttpFile->SendRequest(strHeaders);
}
catch (CInternetException* pException)
{
    pException->m_dwError;
    pException->Delete();
}
pHttpFile->SetReadBufferSize(2048);
CString str;
CString strGetData;
while(pHttpFile->ReadString(strGetData))
{
    str +="\r\n";
    str +=strGetData;
}
CString fileName("index.html");
CFile file(fileName,CFile::modeCreate | CFile::modeWrite);
file.Write(str,str.GetLength());
file.Close();
pHttpFile->Close();
delete pHttpFile;
pHttpConnect->Close();
delete pHttpConnect;
sess.Close();
return TRUE;

1 个答案:

答案 0 :(得分:1)

有几个Linux库实现了HTTP客户端API,可用于在C或C ++中实现HTTP / HTTPS请求。

他们的祖父都是W3C自己的libwww:

http://www.w3.org/Library/

更新的HTTP / HTTPS客户端库是libcurl:

http://curl.haxx.se/libcurl/

其中任何一个都可用于在C或C ++中实现HTTP / HTTPS客户端。但是,在所有情况下,在使用它们之前,您需要了解HTTP / HTTPS协议的工作;特别是在证书验证和验证方面的HTTPS。

这两个库都很常见,而且大多数Linux发行版都已打包它们。您可能已经安装了其中一个或两个。