【问题标题】:FileNotFoundException when using HttpURLConnection to read output from elasticsearch使用 HttpURLConnection 从 elasticsearch 读取输出时出现 FileNotFoundException
【发布时间】:2020-08-21 11:24:18
【问题描述】:

设置:我设置了一个弹性搜索数据库并创建了一个快照。不必知道它是什么,知道它使用 http 方法接收命令就足够了。如果我在控制台中执行此操作,我会使用 curl。 例如,要删除快照,我会使用

curl -X DELETE "localhost:9200/_snapshot/bck/sn5?pretty"

(?pretty 只是格式化输出,否则它将全部在一行中)

这会给我这样的输出:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "snapshot_missing_exception",
        "reason" : "[bck:sn5] is missing"
      }
    ],
    "type" : "snapshot_missing_exception",
    "reason" : "[bck:sn5] is missing"
  },
  "status" : 404
}

现在我正在尝试在 java 中做到这一点。正如我所读到的,我需要一个 inputStream 来读取输出。

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class main {

    public static void main(String[] args) throws IOException {
        String urlTarget = "http://localhost:9200/_snapshot/bck/sn5";
        URL url = new URL(urlTarget);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("DELETE");
        InputStream inputStream = connection.getInputStream();
        //read the data
    }
}

但这会导致输入流出现 FileNotFoundException。 但是,我可以打印 connection.getResponse(),这会导致“未找到”。

所以,我的简单问题是,如何读取我在 java 代码中使用 curl 可以看到的输出?

编辑:在切换到 connection.getErrorStream 的建议之后,当我想初始化 bufferedReader 时,我得到了 NullPointerException。

新的sn-p:

InputStream inputStream = connection.getErrorStream();
//read the response
BufferedReader rdr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuffer output = new StringBuffer();
while ((inputLine = rdr.readLine()) != null) {
    output.append(inputLine + "\n");
}
rdr.close();

谢谢!

【问题讨论】:

    标签: java elasticsearch httpconnection


    【解决方案1】:

    您从getInputStream() 收到FileNotFoundException,因为服务器响应了HTTP 404,实际上是“找不到文件”。

    如果您想读取响应正文而不考虑 HTTP 错误状态,请在 HttpURLConnection 对象上调用 getErrorStream()getInputStream()

    【讨论】:

    • 好的,但是如果我想使用缓冲阅读器阅读它,我会得到 NullPointerException。我已经编辑了问题。
    • 如果 HTTP 响应不是错误或者响应没有内容,getErrorStream() 将返回 null。您需要检查这些情况并相应地调整程序的行为。旧的 Javadoc 链接,但我怀疑这个特定的 API 发生了很大变化:docs.oracle.com/javase/8/docs/api/java/net/…
    • 嗯,好的。但它必须返回一些东西,否则 curl 将无法为相同的请求显示它......
    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多