package javaurlconnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import java.util.logging.Logger; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaURLConnection { public static void main(String[] args) { try { URL url = new URL("http://java-buddy.blogspot.com"); URLConnection urlConnection = url.openConnection(); /* InputStream inputStream = urlConnection.getInputStream(); try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)) { ByteBuffer buffer = ByteBuffer.allocate(1024); while (readableByteChannel.read(buffer) > 0) { String bufferString = new String(buffer.array()); System.out.println(bufferString); buffer.clear(); } } */ //using BufferedReader InputStream inputStream = urlConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader buffReader = new BufferedReader(inputStreamReader); String line; while ((line = buffReader.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException ex) { Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex); } } }
Sunday, March 6, 2016
Read from Internet using URLConnection and BufferedReader
Java example to read from Internet using URLConnection and BufferedReader. Thanks for Tomtom's comment in my last post "Read from Internet using URLConnection and ReadableByteChannel".
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment