Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

2.  Examples

2.1. Read web page via Java

Create a Java project "de.vogella.web.html". The following code will read a webpage from a sever and print it to the console.

				
package de.vogella.web.html;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class ReadWebPage {
	public static void main(String[] args) throws IOException {
		String urltext = "http://www.vogella.de";
		URL url = new URL(urltext);
		BufferedReader in = new BufferedReader(new InputStreamReader(url
				.openStream()));
		String inputLine;

		while ((inputLine = in.readLine()) != null) {
			// Process each line.
			System.out.println(inputLine);
		}
		in.close();
	}
}

			

2.2. Getting the return code from a webpage

HTML return codes are standardized codes which a web server returns if a certain situation has occurred. For example the return code "200" means the HTML request is ok and the server will perform the require action, e.g. serving the webpage.

The following code will access web page and print the return code for the HTML access.

The most important HTML return codes are:

Table 1. 

Return CodeExplaination
200Ok
301Permanent redirect to another webpage
400Bad request
404Not found

				
package de.vogella.web.html;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadReturnCode {
	public static void main(String[] args) throws IOException {
		String urltext = "http://www.vogella.de";
		URL url = new URL(urltext);
		int responseCode = ((HttpURLConnection) url.openConnection())
				.getResponseCode();
		System.out.println(responseCode);
	}
}

			

2.3. Content Type / MIME Type

The Internet media type (short MIME) which is also called Content-type define the type of the web resource. The MIME type is a two-part identifier for file formats on the Internet. For html page the content-type is "text/html".

The following code will check for the return code of an URL and will get the content-type (MIME-Typ) for the web resource.

				
package de.vogella.web.html;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadMimeType {
	public static void main(String[] args) throws IOException {
		String urltext = "http://www.vogella.de";
		URL url = new URL(urltext);
		String contentType = ((HttpURLConnection) url.openConnection())
				.getContentType();
		System.out.println(contentType);
	}
}