Search code examples
jsonhttprequestgodot4

How to get JSON DATA from HTTPRequest in Godot 4.1


Hey I try to get JSON DATA. The code is below. I tried many things, but I am not able to receive a normal JSON.

func makeLoginRequest():

    var url = "https://chocolatefactory-api.dreamstudio.my/login"
    

    var data = {
        "username": "test0001",
        "password": "test0001"
    }
    

    var http_request = HTTPRequest.new()
    

    add_child(http_request)
    

    http_request.connect("request_completed",Callable(self,"_on_request_completed"))
    

    http_request.request(url, ["Content-Type: application/json"], HTTPClient.METHOD_POST, JSON.new().stringify(data))
    

func _on_request_completed(result, response_code, headers, body):

    if response_code == 200:

        print("Anfrage erfolgreich!!")
        var json_data = JSON.new().parse(str(body))
    
            
    else:
        print("Fehler bei der Anfrage. Fehlercode:", response_code)

I always get this:

[123, 10, 32, 32, 34, 116, 111, 107, 101, 110, 34, 58, 32, 34, 101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 73, 85, 122, 73, 49, 78, 105, 73, 115, 73, 110, 82, 53, 99, 67, 73, 54, 73, 107, 112, 88, 86, 67, 74, 57, 46, 101, 121, 74, 49, 99, 50, 86, 121, 83, 87, 81, 105, 79, 105, 73, 49, 90, 71, 82, 108, 77, 68, 65, 119, 77, 106, 100, 108, 89, 87, 77, 48, 90, 68, 77, 120, 79, 71, 81, 53, 78, 106, 103, 51, 90, 87, 85, 53, 89, 87, 74, 108, 77, 122, 107, 48, 77, 105, 73, 115, 73, 110, 86, 122, 90, 88, 74, 117, 89, 87, 49, 108, 73, 106, 111, 105, 100, 71, 86, 122, 100, 68, 65, 119, 77, 68, 69, 105, 76, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 51, 77, 68, 77, 50, 78, 122, 89, 50, 77, 106, 82, 57, 46, 102, 73, 52, 74, 55, 53, 82, 106, 88, 74, 51, 77, 122, 66, 117, 121, 66, 90, 77, 122, 98, 82, 51, 108, 81, 120, 66, 120, 54, 115, 81, 81, 48, 118, 70, 90, 114, 111, 104, 71, 110, 106, 65, 34, 44, 10, 32, 32, 34, 117, 115, 101, 114, 73, 100, 34, 58, 32, 34, 53, 100, 100, 101, 48, 48, 48, 50, 55, 101, 97, 99, 52, 100, 51, 49, 56, 100, 57, 54, 56, 55, 101, 101, 57, 97, 98, 101, 51, 57, 52, 50, 34, 44, 10, 32, 32, 34, 117, 115, 101, 114, 110, 97, 109, 101, 34, 58, 32, 34, 116, 101, 115, 116, 48, 48, 48, 49, 34, 10, 125, 10]


Solution

  • The array you get is the byte representation of the received message as a PackedByteArray. You can use the get_string_from_utf8 method to convert it into a string. For further information the documentation for the HTTPRequest class has an example showing how to get the data of a REST response as Dictionary.