Java URL and URLConnection
The URL class encapsulates the URL address into an object and provides a method to parse the URL address, such as obtaining the uri, host, and port.
URLConnection is a combination of URL objects and Socket connections, making it easier to obtain the connection Socket that initiates a URL request.
1. URL
import java.net.MalformedURLException;import java.net.URL;public class URLDemo { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://192.168.0.124:8080/webapp/index.html?name=lisi"); int port = url.getPort(); String host = url.getHost(); String uri_path = url.getPath(); String request_file = url.getFile(); String query = url.getQuery(); System.out.println("host: "+ host); System.out.println("port: "+ port); System.out.println("uri_path: "+ uri_path); System.out.println("request_file: "+ request_file); System.out.println("query: "+ query); }}
2. URLConnection
You can obtain the URLConnection object through the openConnection () method of the URL. This object is connected to this URL.
That is to say, this object is actually a connected socket. It not only has the ability to parse http response packets, but also has socket-related functions (such as retrieving input streams and output streams ).
For the parsing object only, the URL object parses the URL address and can be considered as parsing http request packets (such as getPort () and getFile ), URLConnection parses http response packets (such as getLastModified () and getHeaderFields ).
Import java. io. IOException; import java. io. inputStream; import java.net. malformedURLException; import java.net. URL; import java.net. URLConnection; public class URLConnectionDemo {public static void main (String [] args) {try {URL url = new URL ("https://www.baidu.com/"); URLConnection urlc = url. openConnection (); System. out. println (urlc. getURL (); // parse the http response packet InputStream is = urlc. getInputStream (); byt E [] buf = new byte [1024]; int len = 0; while (len = is. read (buf ))! =-1) {System. out. println (new String (buf, 0, len) ;}} catch (MalformedURLException e1) {// TODO Auto-generated catch block e1.printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}