使用Qml / Qt Https POST / GET

时间:2012-01-09 15:16:08

标签: qt post https get qml

最近,我正在使用Qt-Qml开发诺基亚手机。我必须向给定的HTTPS Url发出POST请求。 我正在使用QML而我正试图在Javascript中运行它而没有任何运气。

有人对此有所了解吗?可以在QML中使用Javascript来实现吗? 如何在QT中提出建议?

我尝试调用这样的函数:

var http = new XMLHttpRequest()
var url = "myform.xsl_submit";
var params = "num=22&num2=333";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        print("ok");
    }else{
                print("cannot connect");
        }
}
http.send(params);

1 个答案:

答案 0 :(得分:7)

您的if语句错误:该函数被多次调用,但只有一次http.readyState = 4。因此,您打印错误消息,尽管还没有错误。

您应首先检查是否http.readyState = 4,然后查看状态代码。

这是一个最小的工作示例:

import QtQuick 1.1

Rectangle {
    Component.onCompleted: {
        var http = new XMLHttpRequest()
        var url = "http://localhost:8080";
        var params = "num=22&num2=333";
        http.open("POST", url, true);

        // Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", params.length);
        http.setRequestHeader("Connection", "close");

        http.onreadystatechange = function() { // Call a function when the state changes.
                    if (http.readyState == 4) {
                        if (http.status == 200) {
                            console.log("ok")
                        } else {
                            console.log("error: " + http.status)
                        }
                    }
                }
        http.send(params);
    }
}

我使用netcat创建了一个本地伪网络服务器来测试它:

% echo -e 'HTTP/1.1 200 OK\n\n' | nc -l 8080 
POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 15
Connection: Keep-Alive
Accept-Encoding: gzip
Accept-Language: de-DE,en,*
User-Agent: Mozilla/5.0
Host: localhost:8080

num=22&num2=333