All pastes #455381 Raw Edit

Anonymous

public text v1 · immutable
·published 2007-04-24 04:45 UTC
rendered paste body
    public synchronized static long DownloadFile(Socket socket, String URLPath, String LocalFilePath)
    {
        assert (URLPath != null);
        assert (LocalFilePath != null);
        assert (socket != null);
                          
        try {
            
            PrintWriter socketOut = new PrintWriter(socket.getOutputStream(), true);
           
            socketOut.println("GET " + URLPath + " HTTP/1.0");
            socketOut.println("Accept: text/plain, text/html, text/*");
            socketOut.println();
            socketOut.flush();
                        
            String output = "";
            String totalOutput = "";

            BufferedReader socketIn = new BufferedReader( 
                                        new InputStreamReader( socket.getInputStream()));            
             
            while ( (output = socketIn.readLine()) != null) {
                totalOutput += output + "\n";
            }
           
            if (!totalOutput.startsWith("HTTP/1.1 200 OK")) {
            	return -1;
            }

            String dirLocalFilePath = LocalFilePath.substring(0, LocalFilePath.lastIndexOf(File.separator)) + File.separator;

            if (!new File(dirLocalFilePath).exists()) {
                new File(dirLocalFilePath).mkdirs();
            }

            BufferedWriter fileOut  = new BufferedWriter( new FileWriter(LocalFilePath));

            fileOut.write( totalOutput.substring( totalOutput.indexOf("\n\n") + 2) );
            fileOut.close();
           
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return -1;
        }

        return new File(LocalFilePath).length();
    }