QT HTTP接收多个数据包生成图片
生活随笔
收集整理的這篇文章主要介紹了
QT HTTP接收多个数据包生成图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看了看電腦右上角的時間,2017就要徹底流逝了。再瞅了瞅本月的文章數,天啦,只有一篇,近一個月沒有時間學習,沒有時間寫文章,沒有時間休息,總之就是沒時間……好強烈的罪惡感,趕緊抓住最后的幾個小時,補上一文!
我們知道簡單的HTTP請求可以一次返回結果,但對于一些數據量較大的情況,則要分多次返回。
QNetworkAccessManager下的QNetworkReply有readyRead信號,一旦該信號產生,就可以讀取相應的數據并寫入文件中。
對于較大的文件,比如圖片,一個http請求需要分多個數據包返回結果最后才能得到完整的集合。
好在有QNetworkReply::finished。該信號提示我們不會再有數據更新了,此時就可以關閉文件流,結束數據存儲。
如下:
request = new QNetworkRequest ();manager = new QNetworkAccessManager(this);request->setUrl(QUrl("https://static.baydn.com/static/img/icon_head.png"));reply = manager->get(*request);connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT(slotError(QNetworkReply::NetworkError)));// SSL(Secure Sockets Layer 安全套接層), it encrypts data.connect(reply, SIGNAL(sslErrors(QList<QSslError>)),this, SLOT(slotSslErrors(QList<QSslError>)));connect(reply, SIGNAL(finished()), this, SLOT(slotFinished()));數據存儲函數:
void HttpManager::slotReadyRead() {static int time = 0;QByteArray bytes = reply->readAll();QString url = reply->request().url().toString();int fd;if(searchFilesMap(url.toStdString())){ //if fd exist, we append data to local file.fd = filesMap[url.toStdString()];size_t ret = write(fd, bytes.toStdString().c_str(), bytes.size());if(ret <= 0){LOGDBG("write failed: %s", strerror(errno));}}else { //if not exist, we. open and write.string path = getIncomLocalPicPath(url.toStdString());fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC);if(fd == -1){LOGDBG("open failed, %s",strerror(errno));return ;}fchmod(fd, 0777);size_t ret = write(fd, bytes.toStdString().c_str(), bytes.size());if(ret <= 0){LOGDBG("write failed: %s", strerror(errno));}// add info to mapfilesMap[url.toStdString()] = fd;}LOGDBG("%d finished, fd: %d, url: %s",++time, fd, reply->request().url().toString().toStdString().c_str()); }結束函數:
關閉句柄并重命名。
執行:
$ ./http_test [file: httpmanager.cpp, line: 152, funcName: slotReadyRead] 1 finished, fd: 19, url: https://static.baydn.com/static/img/icon_head.png [file: httpmanager.cpp, line: 152, funcName: slotReadyRead] 2 finished, fd: 19, url: https://static.baydn.com/static/img/icon_head.png [file: httpmanager.cpp, line: 152, funcName: slotReadyRead] 3 finished, fd: 19, url: https://static.baydn.com/static/img/icon_head.png [file: httpmanager.cpp, line: 152, funcName: slotReadyRead] 4 finished, fd: 19, url: https://static.baydn.com/static/img/icon_head.png [file: httpmanager.cpp, line: 152, funcName: slotReadyRead] 5 finished, fd: 19, url: https://static.baydn.com/static/img/icon_head.png [file: httpmanager.cpp, line: 181, funcName: slotFinished] 19, finished.總結
以上是生活随笔為你收集整理的QT HTTP接收多个数据包生成图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么程序员喜欢在半夜写代码?
- 下一篇: C/C++指针的经典笔试面试题