[C#] Doing a HTTP Request?

So the following is a simple program in C# which does a http request to example.com and shows the Response in a console:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace EasyHttp
{
    class Program
    {
        static void Main(string[] args)
        {            
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create(
              "http://example.com");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}

When I try to do the same thing on my FiveM server script the request always times out. Is there an alternative way to do that? I just want to get some Information via HTTP requests.

As a reference: this is how it looks in my server script - the doSomething() function isnt important here it’s just a test.

using System;
using System.Threading.Tasks;
// Watch out because there is a CitizenFX Server and CitizenFX Client version!!
using CitizenFX.Core;
using System.Net;
using System.IO;

namespace ServerScript
{
    public class Server : BaseScript
    {
        public Server()
        {
            EventHandlers["test"] += new Action<dynamic>(doSomething);
            DbTest();
        }

        // This is an old test from me: I just tried to trigger this event on
        // the client side ("test") which triggers a clientSideEvent with a 
        // notification - not import for the http-stuff
        void doSomething(dynamic p)
        {
            PlayerList list = new PlayerList();
            foreach (Player player in list)
            {
                player.TriggerEvent("testClient");
            }
        }

        static void DbTest()
        {
            Debug.WriteLine("REQUEST: Webpage example");            
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Debug.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Debug.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
            Debug.WriteLine("REQUEST: got an answer");
        }
    }
}

Alright going to answer my own question because I got it to work! Maybe someone will profit from this.

So the thing is: I cannot get it to work with pure C# - so for an example I just defined another server script file. This time in LUA:


RegisterNetEvent("httpGet")

AddEventHandler("httpGet",function()
	print("Something happening here")
	PerformHttpRequest("http://google.com", function(err, text, headers)
		print("Does actually work!")
	end, 'GET', '', {["Content-Type"] = 'application/json'})
end)

Make sure to define the data and header fields from the HTTP request (it should work without but it doesnt apparently…)

From the server this little snippet can be triggered via: TriggerEvent("httpGet"); and from the Client Side via TriggerServerEvent("httpGet")

Make sure that you do NOT trigger it in the Constructor of your Script-Class (the one that inherits BaseScript) because that will not work.

WOO! FINALLY!

2 Likes