Thursday, March 3, 2016

Read from Internet using URLConnection and ReadableByteChannel

Java example to read from Internet, "http://java-buddy.blogspot.com", using URLConnection and ReadableByteChannel.


Example:
package javaurlconnection;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
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();
                }
            }
        } 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);
        }
    }
    
}



Related:
- Read from Internet using URLConnection and BufferedReader (Thanks Tomtom comment)

2 comments:

  1. Hello,
    you can also use a BufferedReader.
    buffReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("ISO-8859-1")));
    String line;
    while ((line = lBuffReader.readLine()) != null) {
    System.out.println(line);
    }

    ReplyDelete