Java examples for Network:URL Download
retrieve a web page using the URL package, instead of raw socket
import java.io.*; import java.net.*; public class URLClient { public static void main(String argv[]) throws Exception { URL u = new URL("http://java2s.com"); HttpURLConnection uC;/* w w w . j av a 2s . c o m*/ int responseCode; InputStream input; BufferedReader remote; try { uC = (HttpURLConnection) u.openConnection(); System.out.println("port " + u.getPort()); responseCode = uC.getResponseCode(); } catch (Exception ex) { throw new Exception("first : " + ex.getMessage()); } if (responseCode != HttpURLConnection.HTTP_OK) { throw new Exception("HTTP response code : " + String.valueOf(responseCode)); } try { input = uC.getInputStream(); remote = new BufferedReader(new InputStreamReader(input)); String line = new String(); // we will read and print a few lines only line = remote.readLine(); System.out.println(line); line = remote.readLine(); System.out.println(line); line = remote.readLine(); System.out.println(line); } catch (Exception ex) { throw new Exception(ex.getMessage()); } System.out.println(" host : " + u.getHost()); System.out.println(" protocol : " + u.getProtocol()); System.out.println(" port : " + u.getPort()); System.out.println(" allow interaction : " + uC.getAllowUserInteraction()); System.out.println(" allow interaction default : " + uC.getDefaultAllowUserInteraction()); System.out.println("URL : " + uC.getURL()); System.out.println("header : " + uC.getHeaderField("http")); } }