Hello everybody,

I try to find out how to download any file from a URL that doesn't specify. For example:

http://translate.google.com/translate_tts?q=Daniweb

^^This URL directs to an .mp3 file, which is the spoken text by Google Translate.

I have this code already, but it helps only when I use URL with the name of the file, such as:

(THIS URL IS A MADE-UP)

package Download;
import java.io.*;
import java.net.*;
public class SampleFile
{
public static void main(String args[]) throws IOException
{
 
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new 
 
java.net.URL("").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("testplans.pdf");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0)
{
bout.write(data,0,x);
}
bout.close();
in.close();
}
}

Any help will be appreciated, Thanks!

Dani AI

Generated

A few practical points to make the thread more directly useful.

When a URL has no file name the server can still tell the client what to save via HTTP headers (Content-Disposition) or at least the MIME type (Content-Type). A robust Java approach is: use an HTTP client to fetch headers first, look for a Content-Disposition filename (and the RFC5987/6266 filename* form), fall back to the last path segment of the URL, and if there is still no useful name guess an extension from the Content-Type. Browsers do these heuristics automatically; reproducing them in code is what solves ’s case without relying on a hard-coded filename.

A concise Java pattern (uses HttpURLConnection and NIO) — parses Content-Disposition, falls back to URL path, and uses a tiny mapping from MIME type to extension:

import java.io.*;
import java.net.*;
import java.nio.file.*;

public class DownloadWithName {
  public static void main(String[] args) throws Exception {
    URL url = new URL(args[0]);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.setInstanceFollowRedirects(true);
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) throw new IOException("HTTP " + conn.getResponseCode());

    String cd = conn.getHeaderField("Content-Disposition");
    String name = parseFilename(cd);
    if (name == null || name.isEmpty()) {
      String path = url.getPath();
      name = path.substring(path.lastIndexOf('/') + 1);
    }
    if (name == null || name.isEmpty()) {
      String ct = conn.getContentType();
      name = "download" + (guessExt(ct) != null ? "." + guessExt(ct) : "");
    }

    try (InputStream in = conn.getInputStream()) {
      Files.copy(in, Paths.get(name), StandardCopyOption.REPLACE_EXISTING);
    }
  }

  static String parseFilename(String cd) { /* simple parse for filename=; handle quotes */ return (cd==null)?null:cd.replaceAll("(?i).*filename\\*?=\\s*\"?([^\";]+)\"?.*", "$1"); }
  static String guessExt(String ct) {
    if (ct==null) return null;
    ct = ct.split(";")[0].trim().toLowerCase();
    switch (ct) { case "audio/mpeg": return "mp3"; case "application/pdf": return "pdf"; default: return null; }
  }
}

Notes and gotchas: some endpoints require browser-like headers or specific query parameters and may block unknown user agents; set a User-Agent and handle redirects. Servers may provide filename* (encoded charset) which needs URL-decoding. For production use prefer a mature HTTP client (Apache HttpClient, OkHttp) which handles header parsing, redirects and large-stream buffering better. Also respect service terms — if a provider has an official API for text-to-speech, prefer that for sustained use.

Recommended Answers

All 6 Replies

i never ..., but i think that you need search for InputStream

http://download.oracle.com/javase/tutorial/essential/io/index.html

http://www.java2s.com/Code/Java/File-Input-Output/CatalogFile-Input-Output.htm

http://www.java2s.com/Code/Java/Tiny-Application/FileDownloadManager.htm

http://www.java2s.com/Code/Java/Tiny-Application/Browser.htm

Thank for your reply, but the browsers and the download manager also get the same error- they can't download files from unspecific url.

gosh, and you're surprised that you can't access a document if you don't know where to find it?

What'd a taxi driver say when you go to him and tell him "I'd like to visit a friend of mine, but I don't know where he lives or what his name is, I think it was a village with an "e" in the name somewhere"?

gosh, and you're surprised that you can't access a document if you don't know where to find it?

What'd a taxi driver say when you go to him and tell him "I'd like to visit a friend of mine, but I don't know where he lives or what his name is, I think it was a village with an "e" in the name somewhere"?

but the browser like FF can download the file from it, so why I can't?

> http://translate.google.com/translate_tts?q=Daniweb

This URL gives me a 404 (document not found) hence doesn't yield anything. The actual URL should be: http://translate.google.com/translate_tts?ie=UTF-8&q=hello&tl=en&prev=input .

I'd recommend using a property HTTP library which offers sufficient abstraction, something like HttpClient or Resty. A sample test code using can be found .

> http://translate.google.com/translate_tts?q=Daniweb

This URL gives me a 404 (document not found) hence doesn't yield anything. The actual URL should be: http://translate.google.com/translate_tts?ie=UTF-8&q=hello&tl=en&prev=input .

I'd recommend using a property HTTP library which offers sufficient abstraction, something like HttpClient or Resty. A sample test code using can be found .

Thank you very much SOS!
You really helped me- the Resty is what I was looking for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.