Encoding Aware Source Viewer : URLConnection « Network « Java Tutorial






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 MainClass {

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

    String encoding = "ISO-8859-1";
    URL u = new URL("http://www.java2s.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);
    }
  }

}








19.3.URLConnection
19.3.1.All Headers
19.3.2.Chain the InputStream to a Reader
19.3.3.Get files updated last 24 hours
19.3.4.Encoding Aware Source Viewer
19.3.5.Call a servlet from a Java command line application
19.3.6.Read from a URL with buffered stream
19.3.7.Sending a POST Request Using a URL
19.3.8.Read a GIF or CLASS from an URL and save it locally