简体   繁体   中英

How do I make a HTTP request in 4D v12 database

My 4D database has a method that calls an external application to make an HTTP request to an API site, eg https://somewhere.com/api/?key=somekey&param=someparam . The request returns a JSON response. However, the external application only returns a call success or fail. I am not able to extract the JSON response.

My 4D database is still in version 12 and have no plans to migrate yet to latest version. Is there any way for me to make an HTTP request and get the JSON response? I was thinking of using the built-in PHP engine and make cURL call. Has anybody done this in 4D?

I recommend using Keisuke Miyako's OAuth plugin. https://github.com/miyako/4d-plugin-oauth . It comes with a cURL library and a JSON parsing library. I use it to pull JSON data from an api source. It looks like he's depricated the plug-in but has links to the separate components.

http://sources.4d.com/trac/4d_keisuke/wiki/Plugins/

ARRAY LONGINT($optionNames;0)
ARRAY TEXT($optionValues;0)
C_BLOB($inData;$outData)

$url:="https://api.atsomewhere.com/blahblah"
$error:=cURL ($url;$optionNames;$optionValues;$inData;$outData)

If ($error=0)
  $jsonText:=BLOB to text($outData;UTF8 text without length)

  $root:=JSON Parse text ($jsonText)

  JSON GET CHILD NODES ($root;$nodes;$types;$names)

  $node:=JSON Get child by name ($root;"Success";JSON_CASE_INSENSITIVE)
  $status:=JSON Get bool ($node)

  If ($status=1)
   $ResponseRoot:=JSON Get child by name ($root;"Response";JSON_CASE_INSENSITIVE)

   $node1:=JSON Get child by name ($ResponseRoot;"SourceId";JSON_CASE_INSENSITIVE)
   $node2:=JSON Get child by name ($ResponseRoot;"SourceName";JSON_CASE_INSENSITIVE)

   $output1:=JSON Get text ($node1)
   $output2:=JSON Get text ($node2)

End if 

End if

4D v12 has built-in support for PHP. I used the PHP EXECUTE command to call a PHP file. But since 4D v12 PHP does not have native support for cURL I used file_get_contents()

My 4D code is as follows:

C_TEXT($result)
C_TEXT($param1)
C_BOOLEAN($isOk)
$param1:="Tiger"
//someFunction is a function in index.php. $result will hold the JSON return value. 
//I pass value "Tiger" as parameter
$isOk:=PHP Execute("C:\\index.php";"someFunction";$result;$param1)

C:\\index.php contains the PHP script that 4D v12 will run. The code is

<?php
function someFunction($p1){
    $somekey = 'A$ga593^bna,al';
    $api_URL = 'https://somewhere.com/api/?key='. $somekey. '&param='.$p1;
    return file_get_contents($api_URL);
}
?>

This approach is applicable for GET request. But this already serves my purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM