Reprint Please specify : Http://blog.csdn.net/uniquewonderq
How to use it?
Package Com.test;import Java.net.malformedurlexception;import Java.net.url;import java.util.logging.level;import Java.util.logging.logger;public class test{public static void Main (string[] args) { try { //create a URL instance URL baidu=new url ("http://www.baidu.com"); URL url=new url (Baidu, "/index.html?username=wonderq#test"); SYSTEM.OUT.PRINTLN ("agreement:" +url.getprotocol ()); System.out.println ("Host:" +url.gethost ()); If no port number is specified, the default port number is used, at which point the Getport return value is 1 System.out.println ("Port number:" +url.getport ()); System.out.println ("File path:" +url.getpath ()); System.out.println ("file name;") +url.getfile ()); SYSTEM.OUT.PRINTLN ("Relative Path:" +url.getref ()); System.out.println ("Query string:" +url.getquery ()); } catch (Malformedurlexception ex) { Logger.getlogger (Test.class.getName ()). log (Level.severe, NULL, ex);}}}
Output Result:
Run
Protocol: HTTP
Host: www.baidu.com
Port number: 1
File path:/index.html
The name of the file;/index.html?username=wonderq
Relative path: Test
Query string: USERNAME=WONDERQ
Test procedure:
Package Com.test;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstream;import Java.io.inputstreamreader;import Java.net.malformedurlexception;import Java.net.url;import Java.util.logging.level;import Java.util.logging.logger;public class test{public static void Main (string[] args) { try {//Create URL instance url url=new url ("http://www.baidu.com"); The OpenStream () method of the URL gets the byte input stream of the resource represented by the object InputStream Is=url.openstream (); Converts the byte input into a character input stream InputStreamReader isr=new InputStreamReader (IS, "utf-8"); Add buffer BufferedReader br=new BufferedReader (ISR) for character input stream; Defines a string to hold the read data string data= br.readline (); while (Data!=null) {System.out.println (data); Data=br.readline (); } br.close (); Isr.close (); Is.close (); } catch (Malformedurlexception ex) {Logger.getlogger (teSt.class.getName ()). log (Level.severe, NULL, ex); } catch (IOException ex) {Logger.getlogger (Test.class.getName ()). log (Level.severe, NULL, ex); } }}
Output Result:
Save the above results in one text and change the suffix named. html. Then double-click the text.
Such as:
To run the test results:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Socket Application (iii) application of URLs in--java