| Free tutorials for Java, Eclipse and Web programming |
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();
}
}
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 Code | Explaination |
|---|---|
| 200 | Ok |
| 301 | Permanent redirect to another webpage |
| 400 | Bad request |
| 404 | Not 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);
}
}
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);
}
}