Read Data From URL


How To Read URL Data?

Java Raed URL

Java Read Data From URL

Java Read URL Data

Read Data From URL In Java

Read URL Data In Java

package raghuwansh.java;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public final class ReadDataFromURL {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			URL url = new URL("http://www.raghuwansh.com");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(10000);// 10 seconds
			connection.setReadTimeout(50000);// 50 seconds
			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestMethod("GET");
			connection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.1.6) Gecko/20070723 Iceweasel/2.0.0.6 (Debian-2.0.0.6-0etch1)");
			// change the user agent, this is only for example
			connection.setRequestProperty("Content-Type", "text/plain");
			connection.setRequestProperty("charset", "utf-8");
			connection.setUseCaches(false);

			InputStream is = connection.getInputStream();
			int i = -1;
			char c;
			StringBuffer sb = new StringBuffer();

			while ((i = is.read()) != -1) {
				// converts integer to character
				c = (char) i;
				sb.append(c);
			}
			System.out.println(sb.toString());
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

One thought on “Read Data From URL

Leave a Reply

Your email address will not be published. Required fields are marked *


eight × 5 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>