4.URL类的实例
马克-to-win:URL(Uniform Resource Locator-----一致资源查找器)它用来指向Internet上的资源文件,比如 http://java.sun.com:8080/docs/introdiction.htm net包中的URL类提供API来访问Internet上的信息。
比如以上的URL中:
1)协议:http
2)IP 地址或主机名:java.sun.com
3)端口号:8080
4)实际文件路径:docs/introdiction.htm
例:2.4.1
/*no need to have network through to run the program.*/
import java.net.*;
import java.io.*;
public class TestMark_to_win {
public static void main(String[] args) throws Exception {
/* Class URL represents a Uniform Resource Locator, a pointer to a
* "resource" on the World Wide Web. A resource can be something as
* simple as a file or a directory, public URL(String spec)throws
* MalformedURLException: Creates a URL object from the String
* representation.
*/
URL aURL = new URL("http://java.sun.com:8080/docs/books/"
+ "tutorial/index.html");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("default port = " + aURL.getDefaultPort());
System.out.println("port = " + aURL.getPort());
}
}
例:2.4.2
/* This program needs an open connection to run.
*/
import java.net.*;
import java.io.*;
import java.util.*;
public class TestMark_to_win {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("https://www.oracle.com/index.html");
/* public URLConnection openConnection() throws IOException: Returns a
* URLConnection object that represents a connection to the remote
* object referred to by the URL.
*/
URLConnection yahooConnection = yahoo.openConnection();
/* public long getLastModified() Returns the value of the last-modified
* header field. The result is the number of milliseconds since January
* 1, 1970 GMT.
*/
System.out.println("content LastModified"
+ new Date(yahooConnection.getLastModified()));
/*public InputStream getInputStream()throws IOException: Returns an
* input stream that reads from this open connection.
*/
// DataInputStream in = new
// DataInputStream(yahooConnection.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(
yahooConnection.getInputStream()));
String inputLine;
for (int i = 0; i < 25; i++) {
inputLine = in.readLine();
System.out.println(inputLine);
}
in.close();
}
}
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44639795/article/details/102319021