如何从 URL 获取 JSON

how get JSON from URL

我需要使用函数 SSJS fromJson() 读取 URL。 例如,Notes View

的数据访问 API

http://{主机}/{数据库}/api/data/collections/name/{名称}

我该怎么做?

P.S 我认为(我不知道是否属实)如果我使用 Java 代码 (比如这位博主的the class URLReader ,我 失去 authors/readers 功能,因为是我的服务器而不是执行流读取的当前用户?

我会解释为什么我试图理解这个...

我需要在我的应用程序中使用此插件 JQuery Jquery Data Tables。 我需要一个完整的服务器端处理,因为我有超过 10.000 个文档用于任何视图。 这个 jQueryPlugin 将参数发送到特定 URL(我认为是我的 XAgent),以便我想创建一个 XAgent 来读取此参数并解析 JSON API 输出数据。 这是因为我需要快速响应。

Oliver Busse 的解决方案非常慢,因为在 JSON 中加载我视图的所有条目(我有很多条目)并且我等待 30/40 秒进行此操作

我从 PS 了解到,您特别希望从服务器本身获取 JSON,同时保留用户身份验证信息。 Sven 的 post 做了一点,但我认为最可靠的方法是从请求中获取授权和 Cookie headers,然后在你的 URL 请求中传递它们. This answer 与 Java 有很好的基础。你可以扩展它来做这样的事情(当然,我还没有测试过,但它是一个起点):

    HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String authorization = req.getHeader("Authorization");
    String cookie = req.getHeader("Cookie");

    URL myURL = new URL("http://foo.com");
    HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
    if(StringUtil.isNotEmpty(authorization)) {
        myURLConnection.setRequestProperty("Authorization", authorization);
    }
    if(StringUtil.isNotEmpty(cookie)) {
        myURLConnection.setRequestProperty("Cookie", cookie);
    }
    myURLConnection.setRequestMethod("GET");
    myURLConnection.setDoInput(true);
    myURLConnection.setDoOutput(true);
    myURLConnection.connect();
    InputStream is = null;
    try {
        is = myURLConnection.getInputStream();
        String result = StreamUtil.readString(is);
    } finally {
        StreamUtil.close(is);
        myURLConnection.disconnect();
    }

理想情况下,您还可以从请求中获取服务器主机名、协议和端口。

Eric 的评论也很明智:如果这是你可以用普通 类 做的事情,那会更灵活,更少 problem-prone,因为 server-self HTTP调用即可。

正如我在评论中提到的,这种方法强制您的调用通过对 Domino 数据服务的客户端调用进行,否则会使在通过跨 NSF 调用查看(及其内容)(例如- var vwEnt:ViewEntryCollection = session.getDatabase("serverName", "path/myDb.nsf").getView("viewName").getAllEntries();)。

正如我之前在博客 post 中概述的那样,您绝对可以按照 Jesse 的回答(诅咒你打字太快的 Jesse!)概述来实现这一点。我在我的 "grab bag" 工具中包含的东西是 Java class,它是获取 JSON 格式化内容的起点。这是 the link (here's one with basic authorization in a request header) 和 class 我通常从:

package com.eric.awesome;

import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import com.google.gson.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.commons.validator.routines.*;

/**
 * Class with a single, public, static method to provide a  REST consumer
 * which returns data as a JsonObject.
 * 
 * @author Eric McCormick, @edm00se
 * 
 */
public class CustJsonConsumer {
    /**
     * Method for receiving HTTP JSON GET request against a RESTful URL data source.
     * 
     * @param myUrlStr the URL of the REST endpoint
     * @return JsonObject containing the data from the REST response.
     * @throws IOException
     * @throws MalformedURLException
     * @throws ParseException 
     */
    public static JsonObject GetMyRestData( String myUrlStr ) throws IOException, MalformedURLException {
        JsonObject myRestData = new JsonObject();
        try{

            UrlValidator defaultValidator = new UrlValidator();
            if(defaultValidator.isValid(myUrlStr)){

                URL myUrl = new URL(myUrlStr);
                URLConnection urlCon = myUrl.openConnection();
                urlCon.setConnectTimeout(5000);
                InputStream is = urlCon.getInputStream();
                InputStreamReader isR = new InputStreamReader(is);
                BufferedReader reader = new BufferedReader(isR);
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while( (line = reader.readLine()) != null ){
                    buffer.append(line);
                }
                reader.close();
                JsonParser parser = new JsonParser();
                myRestData = (JsonObject) parser.parse(buffer.toString());

                return myRestData;

            }else{
                myRestData.addProperty("error", "URL failed validation by Apache Commmons URL Validator");
                return myRestData;
            }
        }catch( MalformedURLException e ){
            e.printStackTrace();
            myRestData.addProperty("error", e.toString());
            return myRestData;
        }catch( IOException e ){
            e.printStackTrace();
            myRestData.addProperty("error", e.toString());
            return myRestData;
        }
    }
}

要从 SSJS 作为 POJO 调用,您需要执行如下操作:

importPackage(com.eric.awesome);

var urlStr = "http://{host}/{database}/api/data/collections/name/{name}";
var myStuff:JsonObject = CustJsonConsumer.GetMyRestData(urlStr);