Save (download) a file via HTTP

From CodeCodex

Revision as of 03:28, 29 December 2006 by WikiSysop (Talk | contribs)

Implementations

Java

Make sure your class imports these packages:

import java.io.*;
import java.net.*;

Then use this method:

public static boolean downloadFileFromURL(String fetchUrl, String cookie, String savePathAndFilename)
throws IOException,FileNotFoundException,IOException {
    
    HttpURLConnection c;
    
    //save file    	
    URL url = new URL(fetchUrl);
    c = (HttpURLConnection)url.openConnection();
	
    //set cache and request method settings
    c.setUseCaches(false);
    c.setDoOutput(false);
	
    //set other headers
    c.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
    c.setRequestProperty ("Cookie", cookie);
	
    //connect
    c.connect();
	
    BufferedInputStream in = new BufferedInputStream(c.getInputStream());

    OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(savePathAndFilename)));
    byte[] buf = new byte[256];
    int n = 0;
    while ((n=in.read(buf))>=0) {
       out.write(buf, 0, n);
    }
    out.flush();
    out.close();
   
    return true;	    
}

OCaml

open Http_client.Convenience

let get_and_print url =
  let s = http_get url in
  print_string s;
  flush stdout