Https POST / GET with Qml/Qt

16,750

Your if statement is wrong: The function is called several times, but only one time http.readyState = 4. So, you print error messages although there's no errors yet.

You should first check if http.readyState = 4, and then look at the status code.

Here is a minimal working example:

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);
    }
}

I created a local pseudo-webserver with netcat to test it:

% 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
Share:
16,750
fran
Author by

fran

Updated on June 12, 2022

Comments

  • fran
    fran almost 2 years

    Recently I'm working on Nokia mobiles using Qt-Qml. I have to make a POST request to a given HTTPS Url. I'm using QML and I'm trying to do it in Javascript without any luck.

    Anyone has an idea about it? It's possible to do it using Javascript in QML? Any advise on how to make it in QT?

    I tried calling a function like this:

    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);
    
  • hiddenbit
    hiddenbit over 12 years
    @fran Oh, ok :) But I found something different, that may cause the error message, too...
  • fran
    fran over 12 years
    Yes, you're right! thank you anyway..im still struggling doing requests..but no way