ono
ono

Reputation: 3102

FileNotFoundExceptiom on a valid Url

I'm receiving the error on InputStream in = c.getInputStream(); I'm specifically downloading a pdf from a given url. I've checked that it exists by opening it in the browser. Any reason why it's not finding the file?

public class PdfDownloader {

  public static void DownloadFile(String fileURL, File directory) {
      try {

        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Views: 82

Answers (1)

foibs
foibs

Reputation: 3406

Add c.setDoInput(true); before the c.connect(); line, to tell the connection object that you want to receive the server reponse.

Also you may want to change the c.setDoOutput(true); to c.setDoOutput(false); since you are not setting a body for your request (usually, setDoOutput is not needed on get requests)

Upvotes: 1

Related Questions