【发布时间】: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