AlliedModders

AlliedModders (https://forums.alliedmods.net/index.php)
-   Extensions (https://forums.alliedmods.net/forumdisplay.php?f=134)
-   -   REST in Pawn 1.3 - HTTP client for JSON REST APIs (Updated 2021/08/22) (https://forums.alliedmods.net/showthread.php?t=298024)

slekenda 11-07-2017 09:39

Re: REST in Pawn - Communicate with JSON REST APIs
 
Hello!

I'm having a problem with my Post command. My server gets the post JSON data, but the plugin won't execute the function after. I'm calling DoSomething() function in OnPluginStart(). My code:
PHP Code:

public void DoSomething(){
    
PrintToServer("We are in DoSomething");
    
httpClient = new HTTPClient("http://ip.to.my.server");

    
JSONObject port = new JSONObject();
    
port.SetInt("port"iPort);

    
httpClient.Post("api/get_postfromcsgoserver"portOnPortResponse);

    
PrintToServer("We are in DoSomething2");
    
delete port;

}

public 
void OnPortResponse(HTTPResponse responseany value){
    
PrintToServer("We are in OnPortResponse");
    if(
response.Status != HTTPStatus_Created) {
        
PrintToServer("!= HTTPStatus_Created");
        return;
    }
    if (
response.Data == null){
        
PrintToServer("response.data == null");
        return;
    }


The latter is just a part of the function. I don't get any compilation errors. It won't even print the "We are in OnPortResponse" to the server.

Does connection have to be https?

I get this from my server that the plugin tries to Post so it's working
[07/Nov/2017 14:28:09] "POST /api/get_postfromcsgoserver/ HTTP/1.1" 200 98

Thank you!

ReymonARG 11-07-2017 19:24

Re: REST in Pawn - Communicate with JSON REST APIs
 
You need to turn off the invernation of the server, or enter to the server.

Quote:

Originally Posted by slekenda (Post 2559058)
Hello!

I'm having a problem with my Post command. My server gets the post JSON data, but the plugin won't execute the function after. I'm calling DoSomething() function in OnPluginStart(). My code:
PHP Code:

public void DoSomething(){
    
PrintToServer("We are in DoSomething");
    
httpClient = new HTTPClient("http://ip.to.my.server");

    
JSONObject port = new JSONObject();
    
port.SetInt("port"iPort);

    
httpClient.Post("api/get_postfromcsgoserver"portOnPortResponse);

    
PrintToServer("We are in DoSomething2");
    
delete port;

}

public 
void OnPortResponse(HTTPResponse responseany value){
    
PrintToServer("We are in OnPortResponse");
    if(
response.Status != HTTPStatus_Created) {
        
PrintToServer("!= HTTPStatus_Created");
        return;
    }
    if (
response.Data == null){
        
PrintToServer("response.data == null");
        return;
    }


The latter is just a part of the function. I don't get any compilation errors. It won't even print the "We are in OnPortResponse" to the server.

Does connection have to be https?

I get this from my server that the plugin tries to Post so it's working
[07/Nov/2017 14:28:09] "POST /api/get_postfromcsgoserver/ HTTP/1.1" 200 98

Thank you!


Mitchell 11-08-2017 00:22

Re: REST in Pawn - Communicate with JSON REST APIs
 
Quote:

Originally Posted by ReymonARG (Post 2559151)
You need to turn off the invernation

I think you mean Hibernation.

slekenda 11-08-2017 03:12

Re: REST in Pawn - Communicate with JSON REST APIs
 
Quote:

Originally Posted by ReymonARG (Post 2559151)
You need to turn off the invernation of the server, or enter to the server.

Thank you! I have been wondering this now for a while. This was the problem, I never joined the server. And it's hibernation :)

ReymonARG 11-08-2017 11:01

Re: REST in Pawn - Communicate with JSON REST APIs
 
I Hope that plugin author change to server think and not the game frame

CrazyHackGUT 02-09-2018 15:46

Re: REST in Pawn - Communicate with JSON REST APIs
 
So, i forked this extension 31 oct. 2017, and made small changes.
  • Fixed segfault
  • Added timeout connection and waiting response, "Follow location" settings in HTTPClient methodmap.
  • IChangeableForward removed, now extension uses IPluginFunction.
  • Callback modified: added ability for receive error string.
    Code:

    public void OnRequestFinished(HTTPResponse hResponse, any iData, const char[] szError) {
        if (szError[0] != 0) {
            LogError("Error received when processing request: %s", szError);
            return;
        }

        // handle response...
    }

    But you can still use this old function prototype, without receiving error message:
    Code:

    public void OnRequestFinished(HTTPResponse hResponse, any iData) {
        // handle response...
    }

    But in this case, you should add check:
    Code:

    if (hResponse != null)

You can see source code here. Download binaries here.

muukis 07-08-2018 12:46

Re: REST in Pawn - Communicate with JSON REST APIs
 
Sorry if this has been asked before, but...
Is there a way to allow the use of self signed SSL certificates? I am getting a BADCERT_CN_MISMATCH error when using a self signed HTTPS URI rest api.

Code:

L 07/08/2018 - 19:32:20: [RIPEXT] HTTP request failed: Cert verify failed: BADCERT_CN_MISMATCH

Santi. 07-11-2018 19:56

Re: REST in Pawn - Communicate with JSON REST APIs
 
Excellent job!

muukis 07-13-2018 04:42

Re: REST in Pawn - Communicate with JSON REST APIs
 
I managed to get the self signed certificate to work - Thanks for helping me out at GitHub.

However, I have another problem... this does not work:
Code:

#include <sourcemod>
#include <ripext>

public void OnPluginStart()
{
        PrintToServer("Testing JSONObject...");
        JSONObject obj = new JSONObject();
        obj.SetString("test", "ð");
        decl String:test[10];
        obj.GetString("test", test, sizeof(test));
        delete obj;
        PrintToServer("test: %s", test);
        PrintToServer("Finished testing JSONObject");
}

What the server responds is this:
Code:

sm plugins load test
Testing JSONObject...
L 07/13/2018 - 11:35:58: [SM] Native "JSONObject.GetString" reported: Could not retrieve value for key 'test'
L 07/13/2018 - 11:35:58: [SM] Displaying call stack trace for plugin "test.smx":
L 07/13/2018 - 11:35:58: [SM]  [0]  Line 10, test.sp::OnPluginStart()
[SM] Loaded plugin test.smx successfully.

I am trying to send player name to a REST API. It seems some player names fail to work with the JSONObject. Not always though, and that is what I don't quite understand. I am thinking base64 encoding the names, but I was hoping there was a better solution for this.

Here's another example:
Code:

#include <sourcemod>
#include <ripext>

public void OnPluginStart()
{
        PrintToServer("Testing JSONObject...");
        JSONObject obj = new JSONObject();
        obj.SetString("test1", "We start here...");
        obj.SetString("test2", "ð");
        obj.SetString("test3", ".. and here we are");
        decl String:json[64];
        obj.ToString(json, sizeof(json));
        delete obj;
        PrintToServer("json: %s", json);
        PrintToServer("Finished testing JSONObject");
}

What the server responds is this:
Code:

sm plugins load test
Testing JSONObject...
json: {"test1": "We start here...", "test3": ".. and here we are"}
Finished testing JSONObject
[SM] Loaded plugin test.smx successfully.


SztangaBiceps 08-14-2018 23:19

Re: REST in Pawn - Communicate with JSON REST APIs
 
Doesn't work
I cannot take value from page

DJ Tsunami 08-28-2018 04:00

Re: REST in Pawn - Communicate with JSON REST APIs
 
New release:
  • Possible fix for the crashes (thanks Peace-Maker)
  • Added ConnectTimeout, FollowLocation and Timeout properties to HTTPClient (thanks CrazyHackGUT)
  • Added error message to HTTPRequestCallback
Download

Please let me know if you're still experiencing crashes, as I haven't been able to reproduce them myself.

CrazyHackGUT 08-28-2018 14:10

Re: REST in Pawn - Communicate with JSON REST APIs
 
Well, i'm pleased to that you are back to working out on extension. This is really nice extension.
I'm also glad that part of the functionality was taken from my fork.

Good job!

Mitchell 10-25-2018 17:45

Re: REST in Pawn - Communicate with JSON REST APIs
 
i'm not sure why but now every site I try returns 404 status after the tf2 update today. Was working fine before the update.
Guess express was returning 404 for missing a slight slash '/'

slekenda 11-21-2018 02:31

Re: REST in Pawn - Communicate with JSON REST APIs
 
Hello!

I'm trying to load JSON from a file, but I'm getting an error. Anyone any help?

PHP Code:


    char path
[PLATFORM_MAX_PATH 1];
    
BuildPath(Path_SMpathsizeof(path), "data/match.json");
    
PrintToServer("FileExists %d"FileExists(path));

    
JSONObject data JSONObject.FromFile(path); 

Error:
PHP Code:

"[RIPEXT] Invalid JSON in line -1, column -1: unable to 
open addons/sourcemod/data/match.json: No such file or directory" 

PrintToServer("FileExists %d", FileExists(path)); <- This prints "FileExists: 1"

File:
PHP Code:

{
    
"map""de_dust2",
    
"uuid""awawras4aw4as4sa"


EDIT: Apparently when I add the absolute path of the JSON file to "JSONObject data = JSONObject.FromFile(path);" it works but not with the Path_SM

DJ Tsunami 11-22-2018 11:00

Re: REST in Pawn - Communicate with JSON REST APIs
 
Thanks slekenda, this should be fixed in 1.0.6.

Nerus 12-09-2018 17:41

Re: REST in Pawn - Communicate with JSON REST APIs
 
1 Attachment(s)
How to get nested array from json?

I need to get value of total_time_played

Result
PHP Code:

public void OnTodoReceived(HTTPResponse responseany value)
{
    if (
response.Status != HTTPStatus_OK)
    {
        
ThrowError("Failed to retrieve data from web!");
        return;
    }

    if (
response.Data == null
    {
        
ThrowError("Invalid JSON response!");
        return;
    }

    
// Indicate that the response is a JSON array
    
JSONObject json view_as<JSONObject>(response.Data);
    
JSONObject playerstats view_as<JSONObject>(json.Get("playerstats"));

    
delete json;

    
JSONArray stats view_as<JSONArray>(playerstats.Get("stats"));

    
delete playerstats;

    
JSONObject total_time_played view_as<JSONObject>(stats.Get(2));

    
delete stats;

    
char name[32];
    
total_time_played.GetString("name"name32);

    
int time = -1;

    if(!
StrEqual(name"total_time_played"false))
    {
        
delete total_time_played;

        
ThrowError("Invalid element '%s'"name);

        return;
    }

    
time total_time_played.GetInt("value");
    
    
delete total_time_played;

    if(
time 0)
    {
        
ThrowError("Time was not parsed from JSON file correctly!");

        return;
    }

    
PrintToServer("total_time_played = %d"time);


BTW, @DJ Tsunami can you add something like default value on get.

Matix8981 03-24-2019 09:09

Re: REST in Pawn - Communicate with JSON REST APIs
 
I created simple debugging script in PHP for check if rest in pawn sending POST data to target HTTP but can't see any POST data in apache logs i see request from my csgo server.

Debugging script:
PHP Code:

<?php
    file_put_contents
("file.json"json_encode([$_REQUEST$_GET$_POST]));
?>

Output JSON file:
Code:

[[],[],[]]
Plugin:
PHP Code:

void RequestChecker()
{
    
HTTPClient client = new HTTPClient("PAGE");
    
JSONObject post = new JSONObject();
    
post.SetString("type""csgo");
    
post.SetString("param1""string_first");
    
post.SetString("param2""string_second");
    
    
client.Post("index.php"postRequestCheckerCallback);
    
    
delete post;
}

void RequestCheckerCallback(HTTPResponse responseany value)
{
    if (
response.Status != HTTPStatus_Created)
    {
        
PrintToServer("Error 01");
        return;
    }
    if (
response.Data == null)
    {
        
PrintToServer("Error 02");
        return;
    }
    
    
JSONObject post view_as<JSONObject>(response.Data);
    
char param1[128];
    
post.GetString("param1"param1sizeof(param1));
    
    
PrintToServer("Param one %d"param1);



lugui 09-19-2019 16:22

Re: REST in Pawn - Communicate with JSON REST APIs
 
Hey. I'm trying to read a json object that has a unknown number of values with the function GetString(). As the .inc file says it is suposed to return false on invalid index but it is causing a exception intead.

Min2liz 10-29-2019 02:18

Re: REST in Pawn - Communicate with JSON REST APIs
 
Maybe someone can compile this extension with github request included. Extension really great, but missing HasKey method.

sabdha 12-02-2019 04:41

Re: REST in Pawn - Communicate with JSON REST APIs
 
Thank You For This

DJ Tsunami 12-28-2019 06:00

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
New release:
  • Switched to cURL multi interface with libuv for better performance
  • Added HTTP/2 support
  • Added ability to get response headers
  • Added JSONObject.HasKey native (thanks Rachnus)
  • Fixed memory leaks when a handle cannot be created
  • Fixed percent signs breaking JSON file paths
  • Return false instead of throwing an error if the key was not found in JSONObject.GetString
  • Updated cURL, Jansson and mbedTLS libraries
Download

BlacKisEverywhere 03-06-2020 12:31

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
What is curl "-u" representation

DJ Tsunami 03-06-2020 13:27

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
Setting the Authorization header should work.

https://developer.mozilla.org/en-US/.../Authorization

BlacKisEverywhere 03-06-2020 14:10

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
Quote:

Setting the Authorization header should work.

https://developer.mozilla.org/en-US/.../Authorization
https://i.imgur.com/b9VCtww.png

I think this type of authorization can't be set in header.
I tried to set authorization basic as header but this isn't working.

DJ Tsunami 03-06-2020 14:28

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
So you base64-encoded "username:password" and appended the result after "Basic ", as explained on the page I linked?

Edit: seems to work.

PHP Code:

public void OnPluginStart()
{
    
HTTPClient client = new HTTPClient("https://jigsaw.w3.org/HTTP");
    
client.SetHeader("Authorization""Basic Z3Vlc3Q6Z3Vlc3Q=");
    
client.Get("Basic"OnHTTPResponse);
}

public 
void OnHTTPResponse(HTTPResponse responseany value)
{
    
PrintToServer("[Basic] %d"response.Status);


This returns a 200 response. If you comment out client.SetHeader() it returns a 401 response.

BlacKisEverywhere 03-06-2020 14:42

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
After encode keys auth works correctly. Thanks for help and sorry for waste time

milutinke 03-06-2020 15:02

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
Awesome.
Could you make the Amxx version for CS 1.6?

CrazyHackGUT 03-10-2020 07:22

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2019/12/28)
 
For AMXX you might can use gRIP (GoldSrc REST in Pawn). https://github.com/In-line/grip

mrtn 05-18-2020 14:39

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2020/03/24)
 
Hi DJ Tsunami

Firstly many thanks for making this extension. It is fantastic!

Back in 2017 you mentioned that JSONObject iteration was not possible. I am wondering if this is still the case?

Here is an example of what I'm trying to do:

PHP Code:

{
    
"cvars":{
        
"mp_startmoney""800",
        
"mp_maxmoney""16000",
    }


I would like to iterate over the "cvars" property, extracting both the key and value for further processing.

How would I go about this? Is it possible to retrieve an array of keys from a JSONObject? Alternatively is it possible to extract the keys in a similar fashion to StringMaps, via StringMapSnapshot.GetKey(index)?

Thanks a lot

DJ Tsunami 05-19-2020 03:52

Re: REST in Pawn 1.1 - HTTP client for JSON REST APIs (Updated 2020/03/24)
 
It's still not possible, but your use case is legitimate, so I'll look into it.

splinterz 05-29-2020 04:45

Re: REST in Pawn - Communicate with JSON REST APIs
 
Quote:

Originally Posted by Matix8981 (Post 2644719)
I created simple debugging script in PHP for check if rest in pawn sending POST data to target HTTP but can't see any POST data in apache logs i see request from my csgo server.

Debugging script:
PHP Code:

<?php
    file_put_contents
("file.json"json_encode([$_REQUEST$_GET$_POST]));
?>

Output JSON file:
Code:

[[],[],[]]
Plugin:
PHP Code:

void RequestChecker()
{
    
HTTPClient client = new HTTPClient("PAGE");
    
JSONObject post = new JSONObject();
    
post.SetString("type""csgo");
    
post.SetString("param1""string_first");
    
post.SetString("param2""string_second");
    
    
client.Post("index.php"postRequestCheckerCallback);
    
    
delete post;
}

void RequestCheckerCallback(HTTPResponse responseany value)
{
    if (
response.Status != HTTPStatus_Created)
    {
        
PrintToServer("Error 01");
        return;
    }
    if (
response.Data == null)
    {
        
PrintToServer("Error 02");
        return;
    }
    
    
JSONObject post view_as<JSONObject>(response.Data);
    
char param1[128];
    
post.GetString("param1"param1sizeof(param1));
    
    
PrintToServer("Param one %d"param1);



hi, did u fix this?
i got same error like this..
i got null response.Data and i got empty json on my web server..
i tried to use api tester and its working fine so it should be my sourcemod plugin

Peace-Maker 06-02-2020 06:42

Re: REST in Pawn - Communicate with JSON REST APIs
 
Quote:

Originally Posted by splinterz (Post 2702931)
hi, did u fix this?
i got same error like this..
i got null response.Data and i got empty json on my web server..
i tried to use api tester and its working fine so it should be my sourcemod plugin

You'll have to check the request body in PHP instead of the request parameters. Check this.

The request Content-Type is application/json instead of application/x-www-form-urlencoded.

PHP Code:

$body file_get_contents('php://input');
$data json_decode($body); 


DJ Tsunami 06-21-2020 14:45

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/06/21)
 
New release:
  • Added ability to download and upload files
  • Added ability to iterate over keys in a JSON object
  • Optimized performance (thanks Gunslinger)
Download

mrtn 07-10-2020 17:14

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/06/21)
 
Quote:

Originally Posted by DJ Tsunami (Post 2706744)
New release:
  • Added ability to iterate over keys in a JSON object

Key iteration works perfectly, thanks!

DJ Tsunami 07-17-2020 04:00

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/06/21)
 
Version 1.2.0 did not properly clean up requests, please update to version 1.2.1.

1.2.1 also adds support for 64-bit integers in JSON, thanks to Gunslinger.

foon 07-22-2020 10:39

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/07/16)
 
After uploading a file, should we close the handle or is that done automatically?

Code:

void OnImageUploaded(HTTPStatus status, any value)
{
    delete httpClient;
}


DJ Tsunami 07-22-2020 12:36

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/07/16)
 
No, if your HTTP client is defined globally, there's no reason to delete it. You can just reuse it for future requests.

foon 07-22-2020 18:05

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/07/16)
 
Is there anyway to get the file that was uploaded in "OnImageUploaded". You can pass a value, but you cant pass a string (unless i'm missing something here).

DJ Tsunami 07-23-2020 01:52

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/07/16)
 
You can pass a DataPack as value with any data you want.

DJ Tsunami 09-13-2020 06:05

Re: REST in Pawn 1.2 - HTTP client for JSON REST APIs (Updated 2020/07/16)
 
Minor update:
  • Added x64 and Mac builds
  • Added JSON decoding flags
  • Added ability to limit send and receive speed (thanks Kxnrl)
  • Set default user agent
  • Updated HTTPStatus enum
  • Updated documentation
Download


All times are GMT -4. The time now is 12:59.

Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.