How to Read from URL in Java


Here this example we will prompt user to get URL content in Java.

Source Code

package com.beginner.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class GetURLContent {

	public static void main(String[] args) {
		try {
            
			URL url = new URL("http://www.baidu.com");

			try {
                
				InputStream is = url.openStream();
				InputStreamReader isr = new InputStreamReader(is,"utf-8");

                
				BufferedReader br = new BufferedReader(isr);
				String data = br.readLine();

				while (data!=null){
					System.out.println(data);
					data = br.readLine();
				}
				br.close();
				isr.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

	}

}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments