2016-07-30 19 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請求。但這已經符合我的目的。

相關問題