HTTP之Cache-Control基本概念以及实例(C++ Qt实现)
目錄
?
?
基本概念
實例
?
基本概念
注意:這是頭只是限制性的,約束性的,并不是強制性的;
Cache-Control
可緩存性:
public:服務器返回給瀏覽器中Cache-Control中設置了public,代表這個http請求所經過的路徑中(包括中間的http
代理服務器,以及客戶端瀏覽器)都進行緩存;
private:只有發(fā)起請求的瀏覽器,有緩存存在;
no-cahce:每次發(fā)起請求都要在服務器那邊驗證下,如果服務器能讓瀏覽器使用本地緩存,才能使用
到期
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_NAMESPACEnamespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic: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_Hmain.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
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的HTTP之Cache-Control基本概念以及实例(C++ Qt实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QML笔记-对QML中信号与槽的基本认识
- 下一篇: Java web中使用JQuery加载某