我尝试使用downloadURL函数获取以下url,如下所示:
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();
}
答案 0 :(得分:2)
您设置了错误的Content-Type标头。您提供的值适合更多用户代理标题
答案 1 :(得分:1)
关闭,但您没有设置正确的标题。你需要这样做:
request.setRawHeader("User-Agent", "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)" );