Example #1
0
void HttpDownload::slotResponseHeaderReceived( const QHttpResponseHeader & resp ){

    QString contentLength = resp.value("Content-Length");

    if( !contentLength.isEmpty() ){
        long length = contentLength.toLong();
    }

    //user define!!
    if(!this->fileName.isEmpty())
            return;

    QString disposition = resp.value("Content-Disposition");

    disposition.replace(" " ,"",Qt::CaseInsensitive);
    QStringList list = disposition.split(";");

    QString fileName = "";

    QRegExp exp = QRegExp("[ ]*[filename][ ]*=[ ]*.*");
    exp.setCaseSensitivity(Qt::CaseInsensitive);

    for(int i = 0 ; i < list.size() ; i ++){
            QString tempStr = list.value(i);
            if( tempStr.contains(exp)) {
                    exp = QRegExp("[ ]*filename[ ]*=[ ]*");
                    exp.setCaseSensitivity(Qt::CaseInsensitive);
                    fileName = tempStr.remove(exp);
                    break;
            }
    }
    if(!fileName.isEmpty()){
            this->fileName = fileName;
    }
}
void FeedFetcher::readData(const QHttpResponseHeader& response_header) {
    if(!impl_->current_feed_.get())
        return;
    int statusCode =  response_header.statusCode();
    qDebug() << statusCode;
    if (statusCode == 200) {
        //TODO in order to insert CDATA to invalid XML atom,
        //we need capture data of full page
        bytes_.append(impl_->http_->readAll());
//         qDebug() << bytes_.size() << " bytes received.";
        // insert CDATA FLAG if not exists
    } else if ((statusCode >300 || statusCode <300)
        && (response_header.hasKey("location") || response_header.hasKey("Location"))) {
        qDebug()<<response_header.statusCode();
        QUrl location = QUrl(response_header.value("location"));
        if (location.isEmpty()) {
            location = QUrl(response_header.value("Location"));
        }
        qDebug() << location;
        impl_->http_.get()->setHost(location.host(),80);
        impl_->connection_id_ = impl_->http_.get()->get(location.toString());
    } else if (statusCode == 404) {
       //NOTE: Do Nothing
       qDebug() << "404 !!";
    } else {
        qDebug() << "Received non-200 response code: "
                 << statusCode << response_header.toString();
    }
}
void BrisaMSearchClientCP::datagramReceived() {
    while (udpListener->hasPendingDatagrams()) {

        QByteArray Datagram;

        Datagram.resize(udpListener->pendingDatagramSize());
        udpListener->readDatagram(Datagram.data(), Datagram.size());

        QString temp(Datagram);
        QHttpResponseHeader *response = new QHttpResponseHeader(temp);

        if (response->statusCode() == 200) {
            QString usn = response->value("usn");
            if (usn.startsWith("uuid:")) {
                qDebug() << "BrisaMSearch received MSearch answer from "  << usn << "";
                emit msearchResponseReceived(response->value("usn"),
                                             response->value("location"),
                                             response->value("st"),
                                             response->value("ext"),
                                             response->value("server"),
                                             response->value("cache-control"));
            } else {
                qDebug() << "BrisaMSearch received MSearch from " << response->value("location")
                         << " but it does not start with string \"uuid:\". USN field is " << usn;
            }
        }

        delete response;
    }
}
Example #4
0
void HttpGet::httpResponseHeader(const QHttpResponseHeader &resp)
{
    // if there is a network error abort all scheduled requests for
    // this download
    m_response = resp.statusCode();
   
    // 301 -- moved permanently
    // 302 -- found
    // 303 -- see other
    // 307 -- moved temporarily
    // in all cases, header: location has the correct address so we can follow.
    if(m_response == 301 || m_response == 302 || m_response == 303 || m_response == 307) {
        //abort without sending any signals
        http.blockSignals(true);
        http.abort();
        http.blockSignals(false);
        // start new request with new url
        qDebug() << "[HTTP] response =" << m_response << "- following";
        getFile(resp.value("location") + m_query);
    }
    else if(m_response != 200) {
        // all other errors are fatal.
        http.abort();
        qDebug() << "[HTTP] Response error:" << m_response << resp.reasonPhrase();
    }

}
Example #5
0
void HttpEngine::handleUploadHeaders(QHttpResponseHeader header)
{
	if(header.statusCode() != 200)
		throw header.reasonPhrase();
	
	qint64 clen = header.value("content-length").toLongLong();
	while(m_strResponse.size() < clen)
		m_strResponse += m_pRemote->read(1024);
	emit finished(false);
}
Example #6
0
void SimpleHttp::readResponseHeader(const QHttpResponseHeader &responseHeader) {
	qDebug("SimpleHttp::readResponseHeader: statusCode: %d", responseHeader.statusCode());

	if (responseHeader.statusCode() == 301)  {
		QString new_url = responseHeader.value("Location");
		qDebug("SimpleHttp::readResponseHeader: Location: '%s'", new_url.toLatin1().constData());
		download(new_url);
	}
	else
	if (responseHeader.statusCode() == 302)  {
		QString location = responseHeader.value("Location");
		qDebug("SimpleHttp::readResponseHeader: Location: '%s'", location.toLatin1().constData());
		/* http_get_id = get( location ); */
		download(location);
	}
	else
	if (responseHeader.statusCode() != 200) {
		qDebug("SimpleHttp::readResponseHeader: error: '%s'", responseHeader.reasonPhrase().toLatin1().constData());
		emit downloadFailed(responseHeader.reasonPhrase());
		abort();
	}
}
void DJDownloadManager::httpResponseHeaderReceived(const QHttpResponseHeader& response )
{
	int status	= response.statusCode();
	djDebug() << "httpResponseHeaderReceived" << status;
	
	QStringList	keys	= response.keys();
	for ( int i = 0; i < keys.size(); i++ ) {
		djDebug() << keys.at(i) << response.value(keys.at(i));
	}
	switch( status ) {
	case 200://normal
		m_file->open( QIODevice::WriteOnly );
		break;
	case 206: {//resume
		m_file->open( QIODevice::WriteOnly | QIODevice::Append );
        QString range	= response.value("content-range");
        //djDebug() << "rang =" << range << range.section("-",0,0);
        range.remove("bytes",Qt::CaseInsensitive).section("-",0,0);
        m_existedFileSize	= range.remove("bytes",Qt::CaseInsensitive).section("-",0,0).toUInt();
		break;
	}
	case 302: {//redirect
		QString url	= QString( response.value("location") );
		QString host,path;
		ExtractHostAndPath( url, host, path );
		//djDebug() << "redirect" << host << path;
		sendHttpRequest( m_file, path.section("/",-1), m_http, host, path );
		break;
	}
	case 416://outof rang,finished
		break;
	default:
		m_file->setFileName("");
		break;
	}
}
Example #8
0
void HttpGet::httpFinished(int id, bool error)
{
    qDebug() << "[HTTP] Request finished:" << id << "Error:" << error
             << "pending requests:" << http.hasPendingRequests();
    if(id == getRequest) {
        dataBuffer = http.readAll();
        emit requestFinished(id, error);
    }

    if(id == headRequest) {
        QHttpResponseHeader h = http.lastResponse();

        QString date = h.value("Last-Modified").simplified();
        if(date.isEmpty()) {
            m_serverTimestamp = QDateTime(); // no value = invalid
            emit headerFinished();
            return;
        }
        // to successfully parse the date strip weekday and timezone
        date.remove(0, date.indexOf(" ") + 1);
        if(date.endsWith("GMT"))
            date.truncate(date.indexOf(" GMT"));
        // distinguish input formats (see RFC1945)
        // RFC 850
        if(date.contains("-"))
            m_serverTimestamp = QLocale::c().toDateTime(date, "dd-MMM-yy hh:mm:ss");
        // asctime format
        else if(date.at(0).isLetter())
            m_serverTimestamp = QLocale::c().toDateTime(date, "MMM d hh:mm:ss yyyy");
        // RFC 822
        else
            m_serverTimestamp = QLocale::c().toDateTime(date, "dd MMM yyyy hh:mm:ss");
        qDebug() << "[HTTP] HEAD finished, server date:" << date << ", parsed:" << m_serverTimestamp;
        emit headerFinished();
        return;
    }
    if(id == getRequest)
        emit requestFinished(id, error);
}
Example #9
0
void DownloadHandler::readResponseHeader( const QHttpResponseHeader &responseHeader )
{
   const QString contentType("Content-Type");
#if USE_TRACE
TRACESTART(DownloadHandler::readResponseHeader)
#endif
   if( (responseHeader.statusCode() >= 300) && (responseHeader.statusCode() < 400) )
   {
      TheMagic *magic = new TheMagic( *mpTheMagic );
      magic->mURL = responseHeader.value("location");
      mpMagicQueue->addMagic( magic );
      mpTheMagic->fail();
   }
   else if( responseHeader.statusCode() != 200 )
   {
      errorMessage( mpTheMagic->mURL + ":" + QString::number( responseHeader.statusCode() ) +
                    " " + responseHeader.reasonPhrase() );
      mpTheMagic->fail();
   }

   if( responseHeader.hasContentType() )
   {
      mpTheMagic->setContentType( responseHeader.contentType() );
   }

   const QString setCookie("Set-Cookie");
   QList<QPair<QString, QString> > values( responseHeader.values() );
   for( int i = 0; i < values.size(); i++ )
   {
      if( !QString::compare(values.at(i).first, setCookie, Qt::CaseInsensitive) )
      {
#if USE_TRACE
TRACEMSG << values.at(i).second;
#endif
         mCookieJar.store( values.at(i).second );
      }
   }
}
Example #10
0
void HttpEngine::handleDownloadHeaders(QHttpResponseHeader header)
{
	switch(header.statusCode())
	{
	case 200:
	{
		if(m_file.pos() && !header.hasKey("content-range"))
		{
			if(m_nSegmentStart < 0)
			{
				// resume not supported
				m_file.resize(0);
				m_file.seek(0);
				
				emit statusMessage(tr("Resume not supported"));
			}
			else
				throw tr("Segmentation not supported by server");
		}
	}
	case 206: // data will follow
	{
		bool bChunked = false;
		if(header.value("transfer-encoding").compare("chunked",Qt::CaseInsensitive) == 0)
			bChunked = true;
		else
		{
			m_nToTransfer = header.value("content-length").toLongLong();
			emit receivedSize(m_nToTransfer+m_nResume);
		}
		
		if(header.hasKey("content-disposition"))
		{
			QString disp = header.value("content-disposition");
			int pos = disp.indexOf("filename=");
			
			if(pos != -1)
			{
				QString name = disp.mid(pos+9);
				
				if(name.startsWith('"') && name.endsWith('"'))
					name = name.mid(1, name.size()-2);
				emit renamed(name);
			}
		}
		
		dataCycle(bChunked);
		emit finished(false);
		
		break;
	}
	case 301 ... 399: // redirect
		emit redirected(header.value("location"));
		break;
	case 416: // Requested Range Not Satisfiable
		m_strError = tr("Requested Range Not Satisfiable - the file has probably already been downloaded");
		emit finished(false);
		break;
	default: // error
		throw header.reasonPhrase();
	}
}
Example #11
0
void HttpComms::headerReceived(const QHttpResponseHeader &resp)
{
    m_statusCode = resp.statusCode();
    m_responseReason = resp.reasonPhrase();

    QString sidkey = "set-cookie";

    if (resp.hasKey(sidkey))
    {
        QRegExp rx("PHPSESSID=(.+);");
        rx.setMinimal(true);
        rx.setCaseSensitivity(Qt::CaseInsensitive);
        if (rx.indexIn(resp.value(sidkey)) >= 0)
        {
            m_cookie = "PHPSESSID=" + rx.cap(1);
            VERBOSE(VB_NETWORK, QString("HttpComms found cookie: %1").arg(m_cookie));
        }
    }


    VERBOSE(VB_NETWORK, QString("Got HTTP response: %1:%2")
                        .arg(m_statusCode)
                        .arg(m_responseReason));
    VERBOSE(VB_NETWORK, QString("Keys: %1")
                        .arg(resp.keys().join(",") ));


    if (resp.statusCode() >= 300 && resp.statusCode() <= 400)
    {
        // redirection
        QString uri = resp.value("LOCATION");
        VERBOSE(VB_NETWORK, QString("Redirection to: '%1'").arg(uri));

        m_redirectedURL = resp.value("LOCATION");
        m_authNeeded = false;
    }
    else if ((resp.statusCode() == 401))
    {
        // Toggle the state of our authentication pending flag
        // if we've gotten this after having tried to authenticate
        // once then we've failed authentication and turning the pending off will allow us to exit.
        m_authNeeded = !m_authNeeded;
        if (m_authNeeded)
        {
            QString authHeader(resp.value("www-authenticate"));

            if (authHeader.startsWith("Digest") )
            {
                if (!createDigestAuth(false, authHeader, &m_curRequest) )
                {
                    m_authNeeded = false;
                    return;
                }
            }
            else
            {
                QString sUser(m_webCredentials.user + ':' + m_webCredentials.pass);
                QByteArray auth = QCodecs::base64Encode(sUser.toLocal8Bit());
                m_curRequest.setValue( "Authorization", QString( "Basic " ).append( auth ) );
            }

            if (m_timer)
            {
                m_timer->stop();
                m_timer->setSingleShot(true);
                m_timer->start(m_timeoutInterval);
            }

            // Not sure if it's possible to receive a session ID or other cookie
            // before authenticating or not.
            if (!m_cookie.isEmpty())
            {
                m_curRequest.setValue("Cookie", m_cookie);
            }

            http->request(m_curRequest);
        }
    }
    else
    {
        m_authNeeded = false;
    }
}