简体   繁体   中英

FileNotFoundException when using HttpURLConnection to read output from elasticsearch

Setup: I've set up an elasticsearch database and created a snapshot. It is not necessary to know what it is, it should be enough to know that it takes commands using http methods. If I do it in the console, I would use curl. For example, to delete a snapshot, I would use

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

(The?pretty just formats the output, otherwise it would be all in one line)

That would give me an output like:

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

Now I am trying to do that in java. As I have read, I need an inputStream to read the output.

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
    }
}

But this results in a FileNotFoundException for the inputstream. However, I can print the connection.getResponse() which here results in "Not Found".

So, my simple question is, how can I read the output that I can see with curl in my java code?

edit: After the suggestions of switching to connection.getErrorStream I get a NullPointerException when I want to initialize the bufferedReader.

New snippet:

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();

Thanks!

You're getting a FileNotFoundException from getInputStream() because the server responded with HTTP 404, which is effectively, "file not found."

If you want to read the response body regardless of HTTP error status, call getErrorStream() vice getInputStream() on the HttpURLConnection object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM