Sunday, March 27, 2016

Java Networking Examples : How To Display Source Code Of A Web Page Using URLConnection

Intro

This examples will demonstrates how to display source code of a web page using URLConnection class.

Examples


package com.freesamplecode.java.networking;

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

public class GetSourceCodeWebDemo {
 public static void main(String[] args){
  try {
   
   //create URL object
   URL url = new URL("http://free-samplecode.blogspot.com/p/java.html");
   
   //open URL connection
   URLConnection urlConnection = url.openConnection();
   
   //get stream of URL 
   InputStream is = urlConnection.getInputStream();
   int i = 0;
   while((i = is.read()) != -1){
    System.out.print((char)i);
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
 }
}

Output

How To Display Source Code Of A Web Page Using URLConnection

Related Posts:

0 comments: