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

How to simulate the browser to login in https website using c++ based on Linux?

各位,我的目标是在Linux的基础上使用C++后台服务程序登陆https网站下载网页。 详细需求如下: (1)连接到“https://www.space-track.org/auth/login” (2)输入用户名和密码才能登录成功 (3)post本网站的一些表单数据 (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;

有几个 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 发行版都已经打包了它们。您可能已经安装了其中一个或两个。