Encode a web page when reading in Java

Description

The following code shows how to encode a web page when reading.

Example


  /*from www  . j  ava  2 s.co  m*/

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

public class Main {

  public static void main(String[] args) throws Exception {

    String encoding = "ISO-8859-1";
    URL u = new URL("http://www.google.com");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int encodingStart = contentType.indexOf("charset=");
    if (encodingStart != -1) {
      encoding = contentType.substring(encodingStart + 8);
    }
    InputStream in = new BufferedInputStream(uc.getInputStream());
    Reader r = new InputStreamReader(in, encoding);
    int c;
    while ((c = r.read()) != -1) {
      System.out.print((char) c);
    }
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode