0

i am trying to hit URL and try to save the XML file into local path but i am not able to do.

code i am using is here

public class T_save { public static void download(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null;

    try {
       URL url = new URL("url");
    //  URL url = new URL(address);
        conn = url.openConnection();
        in = conn.getInputStream();
        File file = new File(address+localFileName);
        FileWriter fileWriter = new FileWriter(file);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            fileWriter.write(line);
        }
        fileWriter.flush();
        fileWriter.close();

    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
        }
    }
}

public static void download(String address) {
    int lastSlashIndex = address.lastIndexOf('\');
    if (lastSlashIndex >= 0 && lastSlashIndex < address.length() - 1) {
        System.out.println(address.substring(0, lastSlashIndex+1)+"\t\t\t"+ 

  address.substring(lastSlashIndex + 1));
        download(address.substring(0, lastSlashIndex+1), address.substring

     (lastSlashIndex + 1));

    } else {
        System.err.println("Could not figure out local file name for "
                + address);
    }
}

public static void main(String[] args) {

    download("C:\\Users\\praveen\\chaithu12.xml");}
    /*
     * for (int i = 0; i < args.length; i++) { download(args[i]); }

     */
 public static class CustomAuthenticator extends Authenticator {



    // for entering password

    protected PasswordAuthentication getPasswordAuthentication() {



        // Get information about the request

        String prompt = getRequestingPrompt();

        String hostname = getRequestingHost();

        InetAddress ipaddr = getRequestingSite();

        int port = getRequestingPort();



        String username = "username";

        String password = "password";



        // Return the information (a data holder that is used by Authenticator)

        return new PasswordAuthentication(username, password.toCharArray());



    }
}
     }
user3280677
  • 75
  • 1
  • 10

1 Answers1

0

You can do like this

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class T_save {
    public static void download(String address, String localFileName) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;

        try {
            URL url = new URL("http://www.w3schools.com/");
        //  URL url = new URL(address);
            conn = url.openConnection();
            in = conn.getInputStream();

            File file = new File(address+localFileName);
            FileWriter fileWriter = new FileWriter(file);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                fileWriter.write(line);
            }
            fileWriter.flush();
            fileWriter.close();

        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }

    public static void download(String address) {
        int lastSlashIndex = address.lastIndexOf('/');
        if (lastSlashIndex >= 0 && lastSlashIndex < address.length() - 1) {
            System.out.println(address.substring(0, lastSlashIndex+1)+"\t\t\t"+ address.substring(lastSlashIndex + 1));
            download(address.substring(0, lastSlashIndex+1), address.substring(lastSlashIndex + 1));

        } else {
            System.err.println("Could not figure out local file name for "
                    + address);
        }
    }

    public static void main(String[] args) {

        download("D://output.xml");
        /*
         * for (int i = 0; i < args.length; i++) { download(args[i]); }
         */
    }
}

I got Ur Point your passing input in this format

download("C:\\Documents and Settings\\ocp\\output.xml");

with ('\') as separator, so that error occurs..To resolve this issue..Two Options

1) you have to replace this line in the above program

int lastSlashIndex = address.lastIndexOf('/');

with
int lastSlashIndex = address.lastIndexOf('\\');

or

2) Don't change anything in the above program

pass input like this with ('/') as separator

download("C://Documents and Settings//ocp//output.xml");

It will run successfully ..

USE This type of Authentication.... Download the common-codec1.1.jar(from here)and place it in classpath

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.codec.binary.Base64;



public class ConnectToUrlUsingBasicAuthentication {

    public static void main(String[] args) {

        try {
            String webPage = "http://google.com";
            String name = "youraddress@gmail.com";
            String password = "urpwd";

            String authString = name + ":" + password;
            System.out.println("auth string: " + authString);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            System.out.println("Base64 encoded auth string: " + authStringEnc);

            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }
            String result = sb.toString();

            System.out.println("*** BEGIN ***");
            System.out.println(result);
            System.out.println("*** END ***");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Let me know if you face any issues

Naren
  • 1,447
  • 1
  • 10
  • 11
  • Hi i Tried but getting Could not figure out local file name for " + c:/users/praveen/praveen.xml – user3280677 Feb 15 '14 at 15:57
  • Hi naren it seems that path is resolved. After inclusing the authenticator class i am getting http 401 eror..trying to check whats went went wrong – user3280677 Feb 16 '14 at 06:52
  • java.io.IOException: Server returned HTTP response code: 401 for URL: URL at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon nection.java:1625) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Http sURLConnectionImpl.java:254) at T_save.download(T_save.java:28) at T_save.download(T_save.java:98) at T_save.main(T_save.java:108) – user3280677 Feb 16 '14 at 08:10
  • after running the program i am getting the error above.. i updated the code in Question which i am using – user3280677 Feb 16 '14 at 08:10
  • check your username and password correctly ... Where ur applying authentication in your code ? – Naren Feb 16 '14 at 08:19
  • I updated the Answer ..change your code accordingly.. it is the way u have to authenticate(using Base64.encodeBase64(authString.getBytes());) ur self before accessing the content – Naren Feb 16 '14 at 08:39
  • Hi i am able to run the code.. but i have i doubt can't we replace the exisiting file.. if i want run this every 3 hours once.. can't i replace it? I mean deleting the exsisting and creating new – user3280677 Feb 16 '14 at 11:35
  • Let me know first...DO you want delete the already existed file..then write a new file...or Just replace the content of the file – Naren Feb 16 '14 at 11:39
  • i want delete it the file and place new file with new content :( – user3280677 Feb 16 '14 at 12:15
  • One more thing code works but after re-trying many times i get below erorjava.net.ProtocolException: Server redirected too many times (20) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon nection.java:1635) – user3280677 Feb 16 '14 at 12:20
  • U replace the code with this File file = new File(address+localFileName); if(file.exists()) file.delete(); file.createNewFile(); FileWriter fileWriter = new FileWriter(file); – Naren Feb 16 '14 at 12:22
  • to resolve that Exception see this http://stackoverflow.com/questions/11022934/getting-java-net-protocolexception-server-redirected-too-many-times-error – Naren Feb 16 '14 at 12:29
  • @user3280677 Is it completed ??. – Naren Feb 21 '14 at 12:07
  • Hi naren i got it thanks a lot.. i have more one doubt which you helped me last time.. can i ask here or need to raise new question – user3280677 Feb 21 '14 at 14:57
  • perviously u help me on cars file.. where out put Maruthi alto 2 marthu vera 2 – user3280677 Feb 21 '14 at 16:21
  • model/ccar Alto verna Maruthi 2 1 can we get output like – user3280677 Feb 21 '14 at 16:23
  • updated in http://stackoverflow.com/questions/21610114/to-get-count-of-values-with-respective-attribute-values-in-xml-using-java.. here i am not able paste correctly – user3280677 Feb 21 '14 at 16:24
  • if the file size is more data is not writing in xml format.. is there any thing needs to be done. – user3280677 Feb 28 '14 at 19:02