Tim Savigar
Tim Savigar

Reputation: 63

API calls from xPage

I have an xPage that uses an Server side Javascript beforePageLoad call to populate some fields from a remote JSON REST service.

Get this error ..... Error calling method 'openConnection()' on java class 'java.net.URL' ECL Permission Denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.net.www.protocol.https")

This works in a web browser. Are there any client settings I need to change or is there a better way to do this so I can also use it in the Notes XPiNC environment?

Code is below ... thanks in advance

var url = "https://api.companieshouse.gov.uk/company/" + CompanyNo;

var url:java.net.URL = new java.net.URL(url);
var urlconn:java.net.URLConnection = url.openConnection();
urlconn.setRequestProperty("Authorization", "Basic xxxxxxxx==");
if (urlconn.getResponseCode() < 400) {
 var reader:java.io.BufferedReader = new java.io.BufferedReader(
                                            new java.io.InputStreamReader(
                                            urlconn.getInputStream())
                                        );
 var inputLine;
    var jsonTxt = "";
    while ((inputLine = reader.readLine()) != null){
        jsonTxt += inputLine;
    }
    reader.close();

    viewScope.Response = fromJson(jsonTxt);
} else {
       /* error from server */

    viewScope.Response = "Error " + urlconn.getResponseCode() + url;
    }

Upvotes: 0

Views: 316

Answers (1)

stwissel
stwissel

Reputation: 20384

There are a few things you need to change in this approach:

  • Don't use the Java classes from SSJS. Wrap your whole logic into a Java bean. It gives you a better development experience and is easier to test
  • UrlConnection is way too low level, and is a headache for https. Use the Apache HTTP client library (which is AFAIK available on the Domino server)

Some sample code should get you started along these lines:

 HttpClient httpclient = new HttpClient();
 HttpMethod httpMethod = new GetMethod( this.targetURL );
 int statusCode = httpclient.executeMethod(httpMethod);
 // TODO Check for statusCode 200
 String result = httpMethod.getResponseBodyAsString();

Also checkout this Baeldung tutorial

Upvotes: 2

Related Questions