2016-07-30 103 views
1

我的4D数据库有一个方法,用于调用外部应用程序向API站点发出HTTP请求,例如, https://somewhere.com/api/?key=somekey&param=someparam。该请求返回一个JSON响应。但是,外部应用程序只会返回调用成功或失败。我无法提取JSON响应。如何在4D v12数据库中发出HTTP请求

我的4D数据库仍然在版本12中,并没有计划迁移到最新版本。有什么办法让我发出HTTP请求并获得JSON响应?我正在考虑使用内置的PHP引擎并进行cURL调用。有没有人在4D中完成这项工作?

回答

2

我推荐使用Keisuke Miyako的OAuth插件。 https://github.com/miyako/4d-plugin-oauth。它带有一个cURL库和一个JSON解析库。我用它从api源文件中提取JSON数据。看起来他已经删除了插件,但是链接到了单独的组件。

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 

结束时,如果

0

4D v12内置了对PHP的支持。我使用PHP EXECUTE命令来调用PHP文件。但是,由于4D V12 PHP不具有卷曲的原生支持我使用的file_get_contents()

我的4D代码如下:

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包含PHP脚本,4D V12将运行。代码是

<?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); 
} 
?> 

此方法适用于GET请求。但这已经符合我的目的。