28 Feb 2021

How to Download Webpage from URL in java?


Today we will know that How to Download a Webpage of Any Website with the Help of JAVA Programing Language?
Sometimes we surf others website, & We get catchy things on their website's webpages. Means something we get interesting thing, like scripting, css etc. which look nice and interactive.

Therefore, we are eager to know their website source code.

Here, this java code will help you to get the source code of any website. Only we have to provide URL of that specific webpage address.

How to Download Webpage from URL?

Below, I have provided Java code.

  • Create URL object, pass the webpage address to the new URL(address) object.
  • Over the URL object, we call URL.openConnection(); which returns URLConnection object which an abstract class.
  • Next to call, URLConnection.connect(); method to connect/established the connection to server.
  • Create an Scanner object, Passing inputstream that we get from URLConnection.getInputStream();

  
  try{
URL url = new URL(domain);
URLConnection urlc = url.openConnection();
urlc.connect();

Scanner sc = new Scanner (urlc.getInputStream()); 

String str = "";
while(sc.hasNext()){

str += sc.next();
}

File filetoc = new File("/sdcard/webpage"+ System.currentTimeMillis()+ ".html");

filetoc.createNewFile();

FileOutputStream fos = new FileOutputStream(filetoc);

fos.write( str.getBytes() );
fos.close();


}catch(Exception e){
e.printStackTrace();
}
  

Reaction:

No comments:

No Comments

COMMENT FROM MESSAGE