Qt provider QTcpSocket and QTcpServer for TCP; QUdpSocket for UDP; QNetworkRequest, QNetworkReply and QNetworkAccessManager for HTTP, FTP

Qt += network

QML URL

Image

import QtQuick 2.0
Image {
    source: "https://upload.wikimedia.org/wikipedia/sl/thumb/7/75/Qt-logo.svg/100px-Qt-logo.svg.png"
}

Qt.createComponent

Qt.createComponent("http://127.0.0.1/panel.qml");

Loader

import QtQuick 2.0
Item{
    Loader{
         source:"http://127.0.0.1/panel.qml";   
    }    
}

MediaPlayer

MediaPlayer{
    id:player;
    source:"http://127.0.0.1/12.mp3";
}

QQmlApplicationEngine

QQmlApplicationEngine engine;
engine.load(Qurl("http://127.0.0.1/main.qml"));

QQuickView

QQuickView viewer;
viewer.setResource(Qurl("http://127.0.0.1/main.qml"));

QML XMLHttpRequest

Attributes

readyState

statusname
0Uninitialized
1Open
2Sent
3Receiving
4Loaded

responseText

HTTP response body

responseXML

HTTP response XML DOM

status statusText

HTTP status code and status text

HTTP_CODE

onreadystatechange

readyState change callback

Methods

  • open(method,url,async,username,password)
  • setRequestHeader(name,value)
  • send(body)
  • abort()
  • getResponseHeader(name)
  • getAllResponseHeaders()
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Window 2.3

Rectangle{
    width: 400;height: 300;
    property var xmlhttp: null;
    TextEdit{
        id:content;
        anchors.fill: parent;
        anchors.bottomMargin: 20;
        textFormat: Text.RichText
        text: ""
    }
    Button{
        id:load;
        text:"Load";
        anchors.bottom: parent.bottom;
        anchors.left: parent.left;
        anchors.leftMargin: 2;
        onClicked: {
            loadHttpUrl();
        }
    }
    TextInput {
        id: url;
        anchors.bottom: load.bottom;
        anchors.left: load.right;
        anchors.leftMargin: 4;
        text: qsTr("https://cn.bing.com")
    }
    function onResultReady(){
        if(xmlhttp.readyState===4){
            console.log(xmlhttp.responseText)
            content.text=xmlhttp.responseText;
        }
    }

    function loadHttpUrl(){
        var sUrl = url.text;
        if(xmlhttp==null){
            xmlhttp= new XMLHttpRequest();
            xmlhttp.onreadystatechange =onResultReady;
        }
        if(xmlhttp.readyState === 0){
            xmlhttp.open("GET",sUrl,true);
            xmlhttp.send(null);
        }
    }
}

Qt C++ Network

  • QNetworkAccessManager
  • QNetworkReply
  • QNetworkRequest
  • Qurl
QNetworkAccessManager m_netmanager;
QNetworkReply * m_reply;
void onFinished();
int main(int argc, char *argv[])
{
QString strUrl("http://cn.bing.com");
QUrl qurl(strUrl);
QNetworkRequest req(qurl);
m_reply = m_netmanager.get(req);
connect(m_reply,SIGNAL(finished()),this,SLOT(onFinished()))
}
void onFinished()
{
    int status = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(status!=200){
        QByteArray data = m_reply->readAll();
    }
}