1 //httpclientdemo.h2 #ifndef Httpclientdemo_h3 #defineHttpclientdemo_h4 5#include <QMainWindow>6#include <QTcpSocket>7 8 namespaceUi {9 classhttpclientdemo;Ten } one a classHttpclientdemo: publicQmainwindow - { - Q_object the - public: - ExplicitHttpclientdemo (qwidget *parent =0); -~Httpclientdemo (); + - Private: +Ui::httpclientdemo *ui; aQtcpsocket *tcpsocket; at QString addr; - - Privateslots: - voidonconnected (); - voidOnreadyread (); - voidondisconnected (); in voidon_clearbutton_clicked (); - voidon_okbutton_clicked (); to }; + - #endif //Httpclientdemo_h
1 //Httpclientdemo.cpp2#include"httpclientdemo.h"3#include"ui_httpclientdemo.h"4 5#include <QDebug>6#include <QFile>7 8Httpclientdemo::httpclientdemo (qwidget *parent):9 Qmainwindow (parent),TenUiNewUi::httpclientdemo) one { aUI->SETUPUI ( this); - -Tcpsocket =NewQtcpsocket ( this); theConnect (tcpsocket, SIGNAL (connected ()), this, SLOT (onconnected ())); -Connect (tcpsocket, SIGNAL (readyread ()), this, SLOT (onreadyread ())); -Connect (tcpsocket, SIGNAL (disconnected ()), this, SLOT (ondisconnected ())); - } + - voidhttpclientdemo::onconnected () + { aQdebug () <<"Connected ."; atQString head ="get/http/1.1\r\n" - "accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n" - //Not to compress - //"accept-encoding:gzip, deflate, sdch\r\n" - "accept-language:zh-cn,zh;q=0.8\r\n" - "connection:keep-alive\r\n" in "Host:"; -Head + = addr +"\ r \ n" to "upgrade-insecure-requests:1\r\n" + "user-agent:mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/55.0.2883.87 safari/537.36\r\n\r\n"; -Qbytearray tmp =head.tolatin1 (); theTcpsocket->Write (tmp.data ()); * } $ Panax Notoginseng voidHttpclientdemo::onreadyread () - { the //Absolute Path +QFile file ("D:\\workspace\\qt\\httpclientdemo\\index.txt"); aFile.Open (qiodevice::append |qiodevice::text); theQtextstream out(&file); +Qdebug () <<"ready read.."; - out<< tcpsocket->ReadAll (); $ out. Flush (); $ file.close (); - } - the voidhttpclientdemo::ondisconnected () - {WuyiQdebug () <<"Disconnected ."; the } - wuhttpclientdemo::~Httpclientdemo () - { about Deleteui; $ } - - voidhttpclientdemo::on_clearbutton_clicked () - { aUi->iplineedit->setText (QString ()); + } the - voidhttpclientdemo::on_okbutton_clicked () $ { theaddr = ui->iplineedit->text (); theTcpsocket->connecttohost (addr, the); the}
1 //main.cpp2#include"httpclientdemo.h"3#include <QApplication>4 5 intMainintargcChar*Argv[])6 {7 qapplication a (argc, argv);8 Httpclientdemo w;9 w.show ();Ten one returna.exec (); a}
Simple HTTP Client Demo