如何使用 HDFS API 从 HDFS 返回文件列表

问题描述

我创建了一个 java 函数来在 HDFS 中打开一个文件。该函数仅用于 API HDFS。我的代码中没有使用任何 Hadoop 依赖项。 我的功能运行良好:

public static openFile()
    {
        System.out.print("main for testing the Hdfs WEB API");
        URL url = new URL("http://URI/webhdfs/v1/PATH_TO_File?op=OPEN");

        try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection() ;
                con.setRequestMethod("GET");
                con.setDoInput(true);
                InputStream in = con.getInputStream();
                int ch;
                while((ch=in.read())!=-1)
                {
                    System.out.print((char) ch);
                }
                
            } catch (IOException e) {
                
                e.printstacktrace();
            }
    }

我正在做一个函数来返回 HDFS 中的文件列表。第二个功能是:

 public static ListFile()
        {
            System.out.print("main for testing the Hdfs WEB API");
            URL url = new URL("http://URI/webhdfs/v1/PATH_TO_File?op=LISTSTATUS");
    
            try {
                    HttpURLConnection con = (HttpURLConnection) url.openConnection() ;
                    con.setRequestMethod("GET");
                    con.setDoInput(true);
                    InputStream in = con.getInputStream();
                    
                    logger.info("list is '{}' ",url.openStream());
                    
                } catch (IOException e) {
                    
                    e.printstacktrace();
                }
        }

能否请您帮帮我,我如何使用流返回 HDFS 中的文件列表以使用扫描仪获取响应?当我在浏览器中运行它们时,知道这些 URL 运行良好。 提前致谢

解决方法

您可以使用与第一个解决方案完全相同的逻辑,但这次使用 StringBuilder 来获取完整响应,然后您需要使用 JSON 库对其进行解析。

InputStream in = con.getInputStream();
int ch;
StringBuilder sb = new StringBuilder();
while((ch=in.read())!=-1) {
    sb.append((char) ch);
}
String response = sb.toString();
// TODO: parse response string 

注意:像 Retrofit / Gson 这样的库会让这更简单