Posted by Unknown on 2:27 PM
Labels:

Viewing html source of a page running on the server:
You can view complete html code of a page running on the server with the help of Java.
This section provides you the complete code of the above program. This program takes a url starting from “http://” otherwise it sends an error message indicating invalid url. In the program, HttpURLConnection is the abstract class of the java.net package. This class extends the URLConnection class of the java.net package and facilitates all same facilities of the URLConnection class with the specific HTTP features specially. getResponseCode() method of the HttpURLConnection class returns an integer value which is the code for the status from the http response message. getResponseMethod() method of the HttpURLConnection class shows the message with the http response code from the server. getHeaderFieldKey(int j) method returns the key for the given jth header field.

import java.io.*;
import java.net.*;

public class ViewSource{
public static void main (String[] args) throws IOException{
System.out.print("Enter url to view html source code: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String url = br.readLine();
try{
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
int code = uc.getResponseCode();
String response = uc.getResponseMessage();
System.out.println("HTTP/1.x " + code + " " + response);
for(int j = 1; ; j++){
String header = uc.getHeaderField(j);
String key = uc.getHeaderFieldKey(j);
if(header == null || key == null)
break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
}
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r = new InputStreamReader(in);
int c;
while((c = r.read()) != -1){
System.out.print((char)c);
}
}
catch(MalformedURLException ex){
System.err.println(url + " is not a valid URL.");
}
catch(IOException ie){
System.out.println("Input/Output Error: " + ie.getMessage());
}
}
}

0 comments: