1 #include "cachedhttp.h"
2 #include "localcache.h"
6 QByteArray requestHash(const HttpRequest &req) {
8 QByteArray s = req.url.toEncoded() + sep + req.body + sep + QByteArray::number(req.offset);
9 if (req.operation == QNetworkAccessManager::PostOperation) {
13 return LocalCache::hash(s);
17 CachedHttpReply::CachedHttpReply(const QByteArray &body, const HttpRequest &req)
18 : bytes(body), req(req) {
19 QTimer::singleShot(0, this, SLOT(emitSignals()));
22 QByteArray CachedHttpReply::body() const {
26 void CachedHttpReply::emitSignals() {
32 WrappedHttpReply::WrappedHttpReply(LocalCache *cache, const QByteArray &key, HttpReply *httpReply)
33 : HttpReply(httpReply), cache(cache), key(key), httpReply(httpReply) {
34 connect(httpReply, SIGNAL(data(QByteArray)), SIGNAL(data(QByteArray)));
35 connect(httpReply, SIGNAL(error(QString)), SIGNAL(error(QString)));
36 connect(httpReply, SIGNAL(finished(HttpReply)), SLOT(originFinished(HttpReply)));
39 void WrappedHttpReply::originFinished(const HttpReply &reply) {
40 qDebug() << reply.statusCode() << reply.url();
41 if (reply.isSuccessful()) cache->insert(key, reply.body());
45 CachedHttp::CachedHttp(Http &http, const char *name)
46 : http(http), cache(LocalCache::instance(name)), cachePostRequests(false) {}
48 void CachedHttp::setMaxSeconds(uint seconds) {
49 cache->setMaxSeconds(seconds);
52 void CachedHttp::setMaxSize(uint maxSize) {
53 cache->setMaxSize(maxSize);
56 HttpReply *CachedHttp::request(const HttpRequest &req) {
57 bool cacheable = req.operation == QNetworkAccessManager::GetOperation ||
58 (cachePostRequests && req.operation == QNetworkAccessManager::PostOperation);
60 qDebug() << "Not cacheable" << req.url;
61 return http.request(req);
63 const QByteArray key = requestHash(req);
64 const QByteArray value = cache->value(key);
65 if (!value.isNull()) {
66 qDebug() << "HIT" << key << req.url;
67 return new CachedHttpReply(value, req);
69 qDebug() << "MISS" << key << req.url;
70 return new WrappedHttpReply(cache, key, http.request(req));