如何使用 Servoy 框架 post JSON 到 URL

How to post JSON to a URL using the Servoy Framework

Servoy 框架不支持调用 URL 的标准方法(例如:AJAX、JQuery 等)。如何将 JSON 对象发布到 URL?

Servoy JavaScript 框架依赖于 http 插件(包含在 Servoy 中)来制作 HTTP 帖子。

这是一些示例代码,说明如何使用 Servoy post JSON 到 API。我还包含了一些基本的错误处理。请参阅代码注释以了解代码的作用:

var sURL = 'http://www.example.com/myapipath/';
var oJSON = {"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]};

var sClient = plugins.http.createNewHttpClient(); // HTTP plugin object
var sPoster = sClient.createPostRequest(sURL); // Post request object

sPoster.addHeader('content-type','application/json'); // required for JSON to be parsed as JSON
sPoster.setBodyContent(JSON.stringify(oJSON));

application.output('Executing HTTP POST request and waiting for response from '+sURL, LOGGINGLEVEL.INFO);

var sResponse = null;
var sResponseData = "";
var nHttpStatusCode = 0;
var sCaughtException = '';

try {
    nHttpStatusCode = (sResponse = sPoster.executeRequest()).getStatusCode(); // POST JSON request to API
}
catch (e) {

    // This handles the case when the domain called does not exist or the server is down, etc.
    // in this case there will be no HTTP status code returned so we must handle this differently 
    // to prevent the Servoy application from crashing

    sCaughtException = e['rhinoException'].getMessage();

    if (-1 != sCaughtException.indexOf('TypeError: Cannot call method "getStatusCode"')) {
        application.output('WARNING: Could not determine HTTP status code. The server might be down or its URL might be invalid.', LOGGINGLEVEL.WARNING);
    }
    else {
        application.output('WARNING: caught unknown HTTP POST exception: '+sCaughtException, LOGGINGLEVEL.WARNING);
    }

}

// SUCCESS!:

if (200 == nHttpStatusCode) { // HTTP Ready Status

    sResponseData = sResponse.getResponseBody(); // Get the server's response text
    application.output('Successful, response received from server:',LOGGINGLEVEL.INFO);
    application.output(sResponseData, LOGGINGLEVEL.INFO);

    // put your code to handle a successful response from the server here

}
else {

    // insert your code to handle various standard HTTP error codes (404 page not found, 403 Forbidden, etc.)

}