2016-03-08 41 views

回答

0

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

以下是如何使用Servoy将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.) 

}