使用HttpURLConnection读取来自elasticsearch的输出时,出现FileNotFoundException

问题描述 投票:0回答:1

设置:我已经建立了Elasticsearch数据库并创建了快照。不必知道它是什么,只要知道它使用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
    }
}

但是这会导致inputstream的FileNotFoundException。但是,我可以打印connection.getResponse(),在此结果为“找不到”。

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

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

新片段:

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个回答
1
投票

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

如果无论HTTP错误状态如何都想要读取响应主体,请在getErrorStream()对象上调用getInputStream()HttpURLConnection

© www.soinside.com 2019 - 2024. All rights reserved.