The URL class encapsulates the URL address into an object and provides methods to resolve the URL address, such as obtaining the uri part, host part, port, etc.
URLConnection is a combination of URL object and Socket connection, making it easier to obtain the connection socket that initiates URL requests.
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
The URLConnection object can be obtained through the openConnection() method of the URL, which is a connection facing this URL.
In other words, this object is actually a connected socket. It not only has the function of parsing http response messages, but also has the functions of the socket (such as obtaining input streams, output streams, etc.).
As far as parsing objects are concerned, the URL object parses the URL address, which can be regarded as parsing http request messages (such as getPort(), getFile(), etc.), while the URLConnection parses the http response messages (such as getLastModified(), getHeaderFields(), etc.).
import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;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 http response message InputStream is = urlc.getInputStream(); byte[] 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(); } }}The above article is based on java URL and URLConnection (detailed explanation) which is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.