Java Network Knowledge
1) Load APPLE (small application) from the network)
Currently, most browsers support Java in the same way. In HTML, there is a special mark at any position of the. html file. This is a reference to a small application. A small application is not restricted by a region. It can be local or anywhere on the Internet. Its location is transparent to users. For the browser, the location is read in, then the small application is located, and runs it. If a small application is located on a remote computer, the browser must load it before it can run.
(2) load images from URLs
First, you must first introduce the URL. It indicates an Uniform Resource Locator, which is the address of some resources on the network. Java programs can use a URL to reference or connect to network resources. For example:
To remotely load a graph, the Java program must first create a URL to include the image address.
URL is a high-level interaction function in Java programs.
Ii. URL and usage
A URL represents a common resource locator. Provide the URL to the Web browser so that it can search for and locate files on the Internet. When writing Java programs, you can also use URLs to search for resources on the Internet. The class group java.net contains a class named URL, which Java can use to represent a URL address.
The difference here is that the URL address represents an Internet address, and the URL object refers to an instance of URL-like in a Java program.
(1) URL Definition
A URL is an abbreviation used to indicate the Uniform Resource Locator. It is a reference to Internet resources (an address ).
A URL not only indicates the name of a file on the network, but also directs to other resources on the network, such as database query and command output. For example:
Http://java.sun.com //
All URLs have two main components:
(1) protocol identifier;
(2) Resource Name.
In the above example, http is the protocol identifier, and // java.sun.com/is the Resource Name.
The Protocol identifier indicates the name of the protocol used to obtain the resource. In this example, Hypertext Transfer Protocol (HTTP) is used in hypertext transfer service. HTTP is only one of the multiple protocols used to access different types of resources on the Internet. Other protocols include file transfer protocol (FTP), gopher, file, and news ).
The Resource Name is the complete address of the resource. The format of the Resource Name is completely dependent on the protocol used, but for most formats, the resource name includes one or more of the following components:
(1) Host Name: name of the machine where the resource is located.
(2) file name: the path of the file on the machine.
(3) port number: The connected port number (usually optional ).
(4) Reference: a reference to an internal resource named anchor. It often refers to a specific location in a file (generally optional ).
In most cases, the host name and file name are required, while the port number and reference are optional. In the above example, java.sun.com is the host name, and the first slash '/' After the colon is short for the file/index.html.
When building any URL, you should put the Protocol identifier first, followed by the colon ':', and then the Resource Name, namely:
ProtocolID: resourceName
The class group java.net contains a class URL, which is used by Java programs to represent a URL address. A Java program can construct a URL object, open a connection to it, and then read and write in the connection.
3. Create a URL
In Java programs, you can create a URL object to represent a URL address. A URL object always points to an absolute URL, but it can be constructed by an absolute URL, a relative URL, or a URL component.
The simplest way to create a URL object is to create a string in the "readable" format that represents the URL address.
In Java, you can use the strings of the preceding text to create a URL object:
URL gamelan = new URL (http://www.linuxaid.com.cn /)
The URL object created in this method represents an absolute URL. An absolute URL contains all the information required to reach the resource. In addition, you can create a URL object from a relative URL address.
(1) Relative URL
A relative URL only contains sufficient information for the resources of another URL (or in another URL context.
In HTML files, relative URLs are often used to specify the resource location. Commit is required:
My Story
Picture of My Pets
These URLs are relative URLs, that is, these URLs are relative to the 1.html file containing these URLs.
In Java, you can specify a relative URL to create a URL object. For example, if the program is already in the URL context, you can simply specify the file name to create a URL for the file on the linuxaid site:
URL linuxaid = new URL (http://www.javaworld.com /);
URL linuxaidanimation = new url(linuxaid,”aid.animation.html ");
The above Code uses another form of construction process like URL, which allows you to create an object by a URL object (Basic URL) and a relative URL.
This construction process can also be used to create a URL object for a famous connection (reference) in a file. For example, the hypothetical file linuxlinuxaid.animation.html contains a famous connection BOTTOM, which is located at the BOTTOM of the file,
You can use the relative URL construction process to create a URL object (in the following statement, the character # Before BOTTOM is required ):
URL linuxaidAnimationBottom = new URL (linuxaid, "# BOTTOM ");
The URL construction process is generally in the following format:
URL (URL baseURL, String relativeURL)
The first parameter is a URL object, specifying the base address of the new URL, and the second parameter is a String object, which is a description of the Resource Name relative to the base address. If baseURL is null, this construction process treats relativeURL as an absolute URL. However, if relativeURL is specified as an absolute URL, baseURL is ignored during the construction process.
(2) Other URL Construction Processes
In addition to the construction process of the class URL, the class URL also provides two other construction processes. When you use a URL, such as an http url, its resource name contains the host name, file name, port number, and
Reference and other components, these construction processes are very useful. If you do not know the String object that contains the complete URL, It is very convenient to use the two construction processes as long as you know the different components of the URL.
If you need to design a network program that allows users to select the protocol, host name, port number, and file name with the mouse, these components can construct a URL. The class URL provides the process of creating a URL using the Protocol, host name, and file name. The following code creates the URL of the linuxaid.animation.html file pointing to the linuxaidsite:
URL linuxaid = new URL ("http", "www.linuxaid.com.cn", "/linuxaid.animation.html ");
This statement is equivalent to URL linuxaid = URL (http://www.linuxaid.com.cn/linuxaid.animation.html. The first parameter is the protocol, the second parameter is the host name, and the last parameter is the path name of the file.
Note: The file name starts with a slash '/', indicating that the file name is relative to the root directory of the host.
Another construction process of the class URL also adds the port number in the parameter list, for example:
URL linuxaid = new URL ("http", www.linuxaid.com, 80, "/linuxaid.animation.html ");
Among them, 80 is the port number, and other parameters are the same as before. This statement creates the following URL object:
Http://www.linunaid.com.cn: 80/linunxaid.animation.html
If you use these procedures to create a URL object, you can use the URL process toString () or toExternalForm () to obtain a String object containing the complete URL address.
(2) MalformedURLException exception
In the two versions of the URL-like construction process, when the parameters passed to them point to an empty or unknown protocol, they all throw a MalformedURLException exception. If you want to capture and handle this exception, you only need to put the URL construction process statement in a try/catch. For example:
Try {
URL url = new URL (....);
} Catch (MalformedURLException e ){
// Exception Handling Code
}
4. Analyze a URL
URL-like provides some URL object query procedures. You can use these to obtain the protocol, host name, port number, and file name contained in a valid URL object. The following describes the functions of these processes:
(1) getProtocol () returns the Protocol identifier component of the URL.
(2) getHost (), returns the host name component of the URL.
(3) getPort (): return the port number component of the URL. If the port is not set,-1 is returned;
(4) getFile (), returns the URL file name component.
(5) getRef () returns the reference component of the URL.
Note that not all URL addresses contain these components. URLs of the class provide these procedures because HTTP URLs contain these components and may be the most commonly used URLs. The class URL is HTTP-centered in a program.
You can use the getXXX () process to obtain URL Information, which is irrelevant to the construction process of the created URL object.
The following is an example program ParseURL, which creates a URL object from a string of a specified URL and analyzes the URL using the URL object access process;
Import java.net .*;
Class ParseURL {
Public static void main (String [] args ){
URL url = null;
Try {
Url = new URL (http://www.ncsa.uiuc.edu: 8080/demoweb/urlprimer.html # INSTALL );
System. out. println ("protocol =" + url. getProtocol ());
System. out. println ("host =" + url. getHost ());
System. out. println ("filename =" + url. getFile ());
System. out. println ("port =" + url. getPort ());
System. out. println ("ref =" + url. getRef ());
} Catch (MalformedURLException e ){
System. err. println ("MalformedURLException:" + e );
}
}
}
The following is the execution result of the program:
Protocol = http
Host = www.ncsa.uinc.edu
Filename =/demoweb/url-primer.html
Port = 8080
Ref = INSTALL
When using getRef (), note that in versions earlier than JDK1.02, getRef () is valid only for the URLs created in the following two constructor processes:
URL (String absoluteURLSpecification );
URL (URL baseURL, String relativeURLSpecification );
For example, if you use the following statement to create a URL:
URL linuxaid = new URL ("http://www.linuxaid.com.cn /");
URL linuxaidAnimationBottom = new url(gamelan,”aid.animation.html # BOTTOM ");
When you call getRef () for linuxaidAnimationBottom, it returns "BOTTOM" correctly ". However, if you use the following statement to create a URL pointing to the same resource:
URL linuxaidAnimationBottom = new url(“http},www.linuxaid.com.cn},linuxaid.animation.html # BOTTOM ");
When getRef () obtains information from the linuxaidAnimationbottom created in the preceding statement, getRef () returns null instead of "BOTTOM ".
5. Read data directly from a URL
After a URL is successfully created, you can call the URL process openStream () to obtain a stream and read the URL content from the stream. The openStream () process returns an InputStream object. Therefore, you can use
Generally, the InputStream process reads data. Section 2.9 describes the I/O classes provided by the Java development environment and their usage.
Reading from a URL is as easy as reading from an input stream. The following Java program openStreamTest uses the process openStream () to get an input stream on the URL http://www.javaworld.com/, and then
The content of the URL is read in the input stream and displayed on the screen.
Import java.net .*;
Import java. io .*;
Class OpenStreamTest {
Public static void main (String [] args ){
Try {
URL url = new URL (http://www.javaworld.com /);
DataInputStream dis = new DataInputStream (url. openStream ());
String str;
While (str = dis. readLine ())! = Null)
System. out. println (str );
Dis. close ();
} Catch (MalformedURLException e ){
System. err... println ("MalformedURLException:" + e );
} Catch (IOException e ){
System. err. pintln ("IOException:" + e );
}
}
}
}
When you run the program, you will see the HTML commands in the HTML file http://www.javaworld.com/to scroll through the window. Or, you may see:
IOException: java.net. UnknownHostException: www.javaworld.com
The above information indicates that you may need to make necessary settings for your system so that your program can find the www.javaworld.com server.
In addition to the process openStream () mentioned above, the class URL also provides the process getContent (), which can directly obtain the resources pointed to by the URL. The program Fetch given below demonstrates the specific getContent () method.
Import java.net .*;
Import java. awt .*;
Import java. io .*;
Import java. awt. image .*;
Public class Fetch {
Public static String fetch (String addr)
Throws MalformedURLException, IOException {
URL url = new URL (addr );
Return (String) (url. getContent ());
}
Public static Image fetchImage (String addr, Component comp)
Throws MalformedURLException, IOException {
URL url = new URL (addr );
Return comp. createImage (ImageProducer) (url. getContent ()));
}
Public static void main (String [] args)
Throws MalformedURLException, IOException {
System. out. println (fetch (args [0]);
}
}
Fetch can only download common text files (non-HTML files or other types of text files ). The Fetch class also includes a process fetchImage (), which can be used to download GIF images or other common formats.
Use the program FetchImageTest given below for testing.
Import java. awt .*;
Import java. awt. image .*;
Import java.net .*;
Import java. io .*;
Public class FetchImageTest extends Frame {
Private Image img;
Public void paint (Graphics g ){
G. drawImage (img, 0, 0, this );
}
Public static void main (String) [] args)
Throws MalformedURLException, IOException {
FetchImageTest window = new FetchImageTest ();
Window. img = Fetch. fetchImage (args [0], window );
Window. resize (300,300 );
Window. show ();
}
}
After compiling the program, you can run the program using the following command:
Java FetchImageTest http://www.xp163.com/Files/BeyondPic/jeeves.sm.gif
Note: Download of common text and image files depends on the internal "content processor" implemented by Java ". In the JDK environment, the two sample programs can work normally, but it does not mean that they can work in other Java implementations. For Java implementations that do not contain the appropriate content processor, these two programs cannot work. If the program encounters an unsupported content type, the program throws an exception and exits.
The two programs are only used to illustrate the getContent () usage of the process. Generally, this is not the best way to load text or images over the network. For example, loadImage () is a better choice for Applet-like processes.
6. connect to a URL
After a URL is successfully created, you can call the openConnection () process of the URL to connect to the URL. After connecting to a URL, a communication link is established between the Java program and the URL through the computer network.
The openConnection () process creates a new URLConnection object (if there is no suitable one), initializes it, connects to the URL, and returns the URLConnection object. If a problem occurs during this process (for example, the server has been closed), openConnetion () throws an IOException.
If you have successfully connected to the desired URL, you can use the URLConnection object to perform read/write operations on the connection, or query information about its content. The following describes how to read and write a URLconnection. The following program GetURLInfo first connects to URLhttp: // www.javaworld.com, and then queries information about the URLConnectction object.
Import java.net .*;
Import. java. io .*;
Import java. util .*;
Public class GetURLInfo {
Public static void printInfo (URLConnection uc ){
Try {
System. out. println (uc. getURL (). toExternalForm () + ":");
System. out. println ("Content Type:" + uc. getContentType ());
System. out. println ("Content Length:" + uc. getContentLength ());
System. out. println ("Last Modified:" + new Date (uc. getLastModified ()));