Unable to make Http reqeust with c#

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By motifransis

Hello,
I’m a beginner in Godot, but worked with Unity.
I’m trying to make an Http request with a few example codes from the documentation,
but i keep getting errors. when i try the examples in GDScript it seems to work, and i cant figure out why with C# it doesn’t.

for example when using this code :

using Godot;
using System;
using System.Text;

public partial class node : Node
{
	  public override void _Ready()
    {
        GetNode("HTTPRequest").RequestCompleted += OnRequestCompleted;
        HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
        httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");
                
    }

    private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
    {
        JsonParseResult json = Json.Parse(Encoding.UTF8.GetString(body));
        GD.Print(json.Result);
    }
}

I’m getting these errors:

 C:\Users\OSUser\Documents\2\node.cs(9,32): error CS1061: 'Node' does not contain a definition for 'RequestCompleted' and no accessible extension method 'RequestCompleted' accepting a first argument of type 'Node' could be found (are you missing a using directive or an assembly reference?) [C:\Users\OSUser\Documents\2\2.csproj]
 C:\Users\OSUser\Documents\2\node.cs(16,9): error CS0246: The type or namespace name 'JsonParseResult' could not be found (are you missing a using directive or an assembly reference?) [C:\Users\OSUser\Documents\2\2.csproj]
 C:\Users\OSUser\Documents\2\node.cs(16,32): error CS0120: An object reference is required for the non-static field, method, or property 'Json.Parse(string, bool)' [C:\Users\OSUser\Documents\2\2.csproj]

When trying to use HTTPRequest object :

using Godot;
using System;

public partial class Node2D : Godot.Node2D
{
    public override void _Ready()
    {
        // Create an HTTP request node and connect its completion signal.
        var httpRequest = new HTTPRequest();
        AddChild(httpRequest);
        httpRequest.RequestCompleted += HttpRequestCompleted;

        // Perform a GET request. The URL below returns JSON as of writing.
        Error error = httpRequest.Request("https://httpbin.org/get");
        if (error != Error.Ok)
        {
            GD.PushError("An error occurred in the HTTP request.");
        }

        // Perform a POST request. The URL below returns JSON as of writing.
        // Note: Don't make simultaneous requests using a single HTTPRequest node.
        // The snippet below is provided for reference only.
        string body = new Json().Stringify(new Godot.Collections.Dictionary
    {
        { "name", "Godette" }
    });
        error = httpRequest.Request("https://httpbin.org/post", null, true, HTTPClient.Method.Post, body);
        if (error != Error.Ok)
        {
            GD.PushError("An error occurred in the HTTP request.");
        }
    }

    // Called when the HTTP request is completed.
    private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
    {
        var json = new Json();
        json.Parse(body.GetStringFromUtf8());
        var response = json.GetData().AsGodotDictionary();

        // Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
        GD.Print((response["headers"].AsGodotDictionary())["User-Agent"]);
    }
}

I get these errors:

 C:\Users\OSUser\Documents\tst\Node2D.cs(9,25): error CS0246: The type or namespace name 'HTTPRequest' could not be found (are you missing a using directive or an assembly reference?) [C:\Users\OSUser\Documents\tst\tst.csproj]
 C:\Users\OSUser\Documents\tst\Node2D.cs(11,35): error CS0103: The name 'HttpRequestCompleted' does not exist in the current context [C:\Users\OSUser\Documents\tst\tst.csproj]
 C:\Users\OSUser\Documents\tst\Node2D.cs(13,17): error CS0176: Member 'Json.Stringify(Variant, string, bool, bool)' cannot be accessed with an instance reference; qualify it with a type name instead [C:\Users\OSUser\Documents\tst\tst.csproj]
 C:\Users\OSUser\Documents\tst\Node2D.cs(17,3): error CS0103: The name 'error' does not exist in the current context [C:\Users\OSUser\Documents\tst\tst.csproj]
 C:\Users\OSUser\Documents\tst\Node2D.cs(17,71): error CS0103: The name 'HTTPClient' does not exist in the current context [C:\Users\OSUser\Documents\tst\tst.csproj]
 C:\Users\OSUser\Documents\tst\Node2D.cs(18,7): error CS0103: The name 'error' does not exist in the current context [C:\Users\OSUser\Documents\tst\tst.csproj]

I would really appreciate your help.

There are a few things that stand out here and while there’s no overall fix, hopefully this puts you on the right path.

C:\Users\OSUser\Documents\tst\Node2D.cs(9,25): error CS0246: The type or namespace name 'HTTPRequest' could not be found (are you missing a using directive or an assembly reference?) [C:\Users\OSUser\Documents\tst\tst.csproj]

The above error is because while GetNode("HTTPRequest") will return the node, it won’t be a HTTPRequest type unless you tell godot. The script does this on the next line:

HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest"); 

…where you can then use the signal:

httpRequest.RequestCompleted += HttpRequestCompleted;

The second script might be failing because it looks like it is named Node2D which is bad (godot usually warns against naming scripts the same as built in objects). Call it MyHttpTest or something else meaningful (and have the filename match). This script will likely work then.

Making HTTP requests — Godot Engine (stable) documentation in English

HTTPRequest — Godot Engine (stable) documentation in English

spaceyjase | 2023-07-06 08:29

Thank you very much.
while changing the name of the class and file didn’t work, changing the first script to :

using Godot;
using System;
using System.Text;

public partial class node : Node
{
	  public override void _Ready()
    {
        HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
        httpRequest.RequestCompleted += OnRequestCompleted;
        httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");

    }

    private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
    {
        JsonParseResult json = Json.Parse(Encoding.UTF8.GetString(body));
        GD.Print(json.Result);
    }
}

now shows me only these errors :

 C:\Users\OSUser\Documents\2\node.cs(17,9): error CS0246: The type or namespace name 'JsonParseResult' could not be found (are you missing a using directive or an assembly reference?) [C:\Users\OSUser\Documents\2\2.csproj]
     C:\Users\OSUser\Documents\2\node.cs(17,32): error CS0120: An object reference is required for the non-static field, method, or property 'Json.Parse(string, bool)' [C:\Users\OSUser\Documents\2\2.csproj]

how can i fix this?

the funny thing is these scripts where just a copy - paste from the documentation you have referenced.

thanks for your help

motifransis | 2023-07-06 09:00

The examples don’t use System.Text:

using Godot;

public partial class MyNode : Node
{
    public override void _Ready()
    {
        GetNode("HTTPRequest").RequestCompleted += OnRequestCompleted;
        HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
        httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");
    }
    private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
    {
        JsonParseResult json = Json.Parse(Encoding.UTF8.GetString(body));
        GD.Print(json.Result);
    }
}

This works verbatim.

spaceyjase | 2023-07-06 09:56

without System.Text i get an error about Encoding.UTF8.GetString(body)
I have tried pasting the exact code but still get the same errors.

I really don’t know what to do, and i can’t find any post on this issue.

motifransis | 2023-07-06 10:42

I’ll try and get some working code for you in a bit; I’m not near a godot install (:o). I’ll check against the docs, which might need an update.

Your editor (vscode, visual studio, rider?) should tell you what the types need to be and help complete namespaces.

spaceyjase | 2023-07-06 11:26

thank you very much!
actually tried with vscode and visual studio but both didn’t have a fix.

motifransis | 2023-07-06 11:54

:bust_in_silhouette: Reply From: spaceyjase

Well, the documentation here isn’t great as the example doesn’t work at all. I apologise for the misleading comments.

Here’s an example that works based on the documentation:

using Godot;
using System.Text;

public partial class HttpRequestTest : Node2D
{
    public override void _Ready()
    {
        var httpRequest = GetNode<HttpRequest>("HTTPRequest");
        httpRequest.RequestCompleted += OnRequestCompleted;
        httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");
    }

    private static void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
    {
        var d = Json.ParseString(Encoding.UTF8.GetString(body)).AsGodotDictionary();
        GD.Print(d["name"]);
    }
}

(prints “4.1-stable” at the time of writing)

I’ll open a PR to update the docs! Hope that gets you going.

THANK YOU!

Was so frustrating…

motifransis | 2023-07-07 05:53