HTTP之Cache-Control基本概念以及实例(C++ Qt实现)
发布日期:2021-06-30 11:00:58 浏览次数:2 分类:技术文章

本文共 2827 字,大约阅读时间需要 9 分钟。

目录

 

 


 

基本概念

注意:这是头只是限制性的,约束性的,并不是强制性的;

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 
QT_BEGIN_NAMESPACEclass 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_H

main.cpp

#include "widget.h"#include 
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 
#include
#include
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 = "" "" "
" "Hello" "" "" "" "

Hello World

" "" ""; 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://it1995.blog.csdn.net/article/details/89603048 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:系统架构师学习笔记-论文摘要部分的写法
下一篇:前端/JS笔记-利用JS/正则判断input是否存数字以及字母加数字

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月09日 19时57分15秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章