001// Copyright (c) 2001 Hursh Jain (http://www.mollypages.org) 002// The Molly framework is freely distributable under the terms of an 003// MIT-style license. For details, see the molly pages web site at: 004// http://www.mollypages.org/. Use, modify, have fun ! 005 006package fc.util; 007 008import java.io.*; 009import java.net.*; 010import java.util.*; 011 012import fc.io.*; 013 014/** 015Network related utils (including HTTP) (the servlet/WebUtil class is for servlet specific utils) 016*/ 017public final class NetUtil 018{ 019/* 020Downloads and saves data from url to specified file. The file should be a 021complete file (including directory information) and the name of the file can 022of course be arbitrary. (construct a file with the same name as the url if 023you need to save the url as-is, with the same name). 024*/ 025public static void downloadAndSaveImage(File output, String url) throws IOException 026 { 027 URL u = new URL(url); 028 InputStream in = u.openStream(); 029 BufferedInputStream bin = new BufferedInputStream(in); 030 031 final int buffer_size = 2056; 032 final byte[] buf = new byte[buffer_size]; 033 034 OutputStream bout = new BufferedOutputStream( 035 new FileOutputStream(output), buffer_size); 036 037 int read = 0; 038 while (true) { 039 read = bin.read(buf, 0, buffer_size); 040 if (read == -1) { 041 break; 042 } 043 bout.write(buf, 0, read); 044 } 045 046 bout.flush(); 047 bout.close(); 048 } 049 050/* 051Returns true if the specified resource exists, false otherwise. 052 053Uses HTTP HEAD method and a return code != 404 054*/ 055public static boolean resourceExists(String url) 056 { 057 boolean exists = false; 058 try { 059 URL u = new URL(url); 060 HttpURLConnection hc = (HttpURLConnection) u.openConnection(); 061 hc.setRequestMethod("HEAD"); 062 hc.connect(); 063 int code = hc.getResponseCode(); 064 exists = code == HttpURLConnection.HTTP_OK; //http code 200 065 } 066 catch (Exception e) { 067 Log.getDefault().error(IOUtil.throwableToString(e)); 068 } 069 070 return exists; 071 } 072 073 074public static void main (String args[]) 075 { 076 Args myargs = new Args(args); 077 myargs.setUsage("-url <url to check exists>"); 078 079 String url = myargs.getRequired("url"); 080 System.out.println("exists: " + resourceExists(url)); 081 } 082 083} 084