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)


Source: http://java-buddy.blogspot.com/

Be the first to comment

Leave a Reply

Your email address will not be published.


*