目录
基本概念
注意:这是头只是限制性的,约束性的,并不是强制性的;
Cache-Control
可缓存性:
public:服务器返回给浏览器中Cache-Control中设置了public,代表这个http请求所经过的路径中(包括中间的http
代理服务器,以及客户端浏览器)都进行缓存;
private:只有发起请求的浏览器,有缓存存在;
no-cahce:每次发起请求都要在服务器那边验证下,如果服务器能让浏览器使用本地缓存,才能使用
到期
max-age=<seconds> //多少秒后到期
s-maxage=<seconds> //当在代理服务器中s-maxage会代替max-age,只有代理服务器会用到他
max-stale=<seconds> //用于服务器返回带的头,即使到期,也使用旧的,只有在seconds结束后,才接收新的资
源
重新验证
must-revalidate 如果到期,必须在原服务端,重新获取数据;
proxy-revalidate 用于代理
其他
no-store //本地和代理服务器都不能存储缓存;每次都要拿新的
no-transform //不允许压缩,格式转换(代理服务器)
实例
这里用Cache-Control: max-age=2000举个例子,让浏览器从缓存中加载页面;
如下:
第一次加载界面:
刷新下:
程序结构如下:
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QTcpServer;
class QTcpSocket;
QT_END_NAMESPACE
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected slots:
void newConnectionSlot();
void errorStringSlot();
void sendMsg();
private:
Ui::Widget *ui;
QTcpServer *m_tcpServer;
QTcpSocket *m_tcpSocket;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QTcpServer>
#include <QDebug>
#include <QTcpSocket>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_tcpServer = new QTcpServer(this);
m_tcpServer->listen(QHostAddress::Any, 83);
connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
connect(m_tcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(errorStringSlot()));
}
Widget::~Widget()
{
delete ui;
m_tcpServer->close();
}
void Widget::newConnectionSlot()
{
qDebug() << "newConnectionSlot() called!";
m_tcpSocket = m_tcpServer->nextPendingConnection();
connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(sendMsg()));
}
void Widget::errorStringSlot()
{
qDebug() << m_tcpServer->errorString();
}
void Widget::sendMsg()
{
QString urlStr = m_tcpSocket->readLine();
qDebug() << urlStr;
QString contentStr = "<html>"
"<head>"
"<title>"
"Hello"
"</title>"
"</head>"
"<body>"
"<h1>Hello World</h1>"
"</body>"
"</html>";
QString str = "HTTP/1.1 200 OK\r\n";
str.append("Server:nginx\r\n");
str.append("Content-Type:text/html;charset=UTF-8\r\n");
str.append("Cache-Control: max-age=2000\r\n");
str.append("Connection:keep-alive\r\n");
str.append(QString("Content-Length:%1\r\n\r\n").arg(contentStr.size()));
str.append(contentStr);
m_tcpSocket->write(str.toStdString().c_str());
}
源码下载地址:
https://github.com/fengfanchen/Qt/tree/master/HTTPCache-ControlDemo