我嘗試使用將downloadURL功能如下得到這個以下網址:如何設置QNetworkReply屬性以獲取正確的NCBI頁面?
http://www.ncbi.nlm.nih.gov/nuccore/27884304
但數據並不如我們可以通過瀏覽器看到的,現在我知道這是因爲一些正確的信息(如瀏覽器類型)是必需的。我怎麼知道我需要設置什麼樣的信息,以及如何設置它? (通過setHeader函數或其他方式??)
在VC++中,我們可以使用CInternetSession和CHttpConnection對象來獲取正確的數據,而不需要設置任何其他詳細信息,在Qt或其他跨平臺C++中是否有類似的方式網絡庫? (是的,我需要的跨平臺特性。)
QNetworkReply::NetworkError downloadURL(const QUrl &url, QByteArray &data) {
QNetworkAccessManager manager;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader ,"Mozilla/5.0 (Windows; U; Windows NT
6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)");
QNetworkReply *reply = manager.get(request);
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QVariant statusCodeV = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
QUrl redirectTo = statusCodeV.toUrl();
if (!redirectTo.isEmpty())
{
if (redirectTo.host().isEmpty())
{
const QByteArray newaddr = ("http://"+url.host()+redirectTo.encodedPath()).toAscii();
redirectTo.setEncodedUrl(newaddr);
redirectTo.setHost(url.host());
}
return (downloadURL(redirectTo, data));
}
if (reply->error() != QNetworkReply::NoError)
{
return reply->error();
}
data = reply->readAll();
delete reply;
return QNetworkReply::NoError; }
通過VC,我們就可以做到這一點,那麼正確的數據在CHttpFile。
CString downloadURL (CString sGetFromURL)
{
// create an internet session
CInternetSession csiSession;
int pos;
BOOL neof;
// parse URL to get server/object/port
DWORD dwServiceType;
CString sServerName;
CString sObject;
INTERNET_PORT nPort;
CHttpConnection* pHTTPServer = NULL;
CHttpFile* pFile = NULL;
AfxParseURL (sGetFromURL, dwServiceType, sServerName, sObject, nPort);
// open HTTP connection
pHTTPServer = csiSession.GetHttpConnection (sServerName, nPort);
// get HTTP object
pFile = pHTTPServer->OpenRequest (CHttpConnection::HTTP_VERB_GET, sObject, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD);
pFile->SendRequest();
}
感謝還是有幫助:)我發現了一些其他的URL來獲取數據。但是,我仍然很高興知道代碼中的問題在哪裏。下次我會知道如何去做^^ – 2010-05-07 00:03:09