Java network programming learning notes (2)

xiaoxiao2021-03-06  40

The second part retrieves data with URL

One. URL class

The simpler method for the Java program positioning and retrieving the data on the network is to use the URL class.

The java.net.url class is an abstraction of the unified resource locator. After the URL object is created, its fields are no longer changing.

Six constructors constructed by java.net.url:

1) Construct URL with a string

Public URL (String Url) Throws Malformedurlexception

2) Construct URL with components

Public URL (String Protocol, String Hostname, String File "Throws Malformedurlexception

This constructor sets the port to -1, so all the default ports of the protocol can be used.

3) Construct URL with components

Public URL (String Protocol, String Host, Int Port, String File "Throws Malformedurlexception

This constructor can specify port with an int variable for unclear cases that the default port is incorrect.

4) Construction relative URL

Public URL (URL Base, String Relative) Throws Malformedurlexception

This constructor constructs absolute URL according to the relative URL and the basic URL

E.g:

Try

{

URL U1 = New URL ("http://metalab.unc.edu/javafaq/index.html");

URL U2 = New URL (U1, "MailingLists.html");

}

Catch (Malformedurlexception E)

{

System.err.Println (e);

}

5) Specify URLStreamHandler

Public URL (URL Base, String Relative, URLSTREAMHANDAL HANDAL) THROWS MALFORMEDUREXCEPTION

This constructor constructs a relative URL with a basic URL and relative part, and then processes the URL with the specified processor.

6) Specify urlstreamhandler

Public URL (String Protocol, String Host, Int Port, String File, UrlstreamHandler Handler) THROWS MALFORMEDUREXCEPTION

This constructor constructs a URL from its component portion and then processes the URL with the specified processor.

In addition to these constructors, there are many other ways to return to the URL object in the Java class library. Most of these are just a simple acquisition method, only the URL that the user may already know, because the user has first used it to create an object.

two. Decomposition URL

The URL can be considered to be composed of five parts:

1) Scheme, or considered an agreement

2) Permissions

Permissions can be further divided into user information, host, and ports.

3) path

4) Reference (REF), also known as a section or a named Anchor

5) Query string

Access the five parts of the URL in read-only mode:

1) Public string getProtocol ()

GetProtocol () method Returns a string that contains a policy of URL: such as "http", "https", "file", etc.

2) Public string gethost ()

The gethost () method returns a String that contains the host name of the URL. 3) Public int getPort ()

GetPort () method returns the port number, which is an int that specified in the URL. If there is no specified port in the URL, the getport () method returns -1, marking the URL does not explicitly specify the port while using the default port of the protocol.

4) Public string getfile ()

The getFile () method returns a String, which contains the path and file part of the URL. From the first "/" of the host name, the symbol before the "#" before another is considered to be the file section.

5) Public string getpath ()

It is the same as getfile () method.

6) Public String getRef ()

getRef () Returns the name anchor portion of the URL. If the URL does not have a named anchor, then this method returns NULL.

E.g:

Try

{

URL u = new url ("http://metalab.unc.edu/javafaq/javafaq.html#xtocid

1902914 "

);

System.out.println ("THE REF OF" U "IS" u.getRef ();

}

Catch (Malformedurlexception E)

{

System.err.Println (e);

}

This code returns, getRef () returned strings XTOCID1902914

7) Public string getQuery ()

The getQuery () method returns the query string of the URL. If the URL does not query the string, then this method returns NULL.

8) Public string getUserInfo ()

Some URLs include user names and even password information. It is located after the policy and the host name, "@" symbols delineate its range. This method returns NULL if the URL does not contain any user information. The Mailto URL will appear exceptions, in the URL such as Mailto: Elharo@metalab.unc.edu, Elharo @ Metalab.Unc.edu is the path, not user information and hostnames.

9) Public string getAuthority ()

GetAuthority () Returns the permissions of the URL. Includes user information, host name, and port.

three. Retrieve data from URL

1) Public Final InputStream OpenStream () THROWS IOEXCEPTION

The OpenStream () method connects the resource of the URL reference to implement all the necessary handshake connections between the client and the server, and returns inputstream from readable data. The data obtained from InputStream is the original (ie, there is no parsed) content of the URL reference file.

2) Public urlConnection openconnection () THROWS IOException

OpenConnection () method Opens a socket to the specified URL and returns a URLConnection object. UrlConnection represents an open connection to a network resource.

3) Public Final Object getContent () THROWS IOEXCEPTION

The getContent () method retrieves the data of the URL reference and attempts to convert it into a type of object.

4) Public Final Object getContent (class [] classes) Throws oException

The overload variable of the getContent () method makes it possible to select the class we want as the return content, which is attempting to return the URL of the URL in the order in the array.

E.g:

URL u = new url ("http://nwu.org");

Class [] Types = new class [3];

Types [0] = String.class;

Types [1] = reader.class;

Types [2] = InputStream.class;

Object o = u.getContent (Types);

Then you must use the InstanceOf test to return to the type of object.

IF (o instanceof string)

{

System.out.println (O);

}

ELSE IF (o instanceof reader)

{

INT C;

Reader r = (reader) C;

While ((c = r.read ())! = -1)

System.out.print (CHAR) C);

}

ELSE IF (o instanceof inputstream)

{

INT C;

InputStream IN = (InputStream) O;

While ((c = in.read ())! = -1)

System.out.write (c);

}

Else

{

System.out.println ("Error: Unexcepted Type" O.getClass ());

}

four. Tool method

1) Public Boolean Samefile (URL Other)

SameFile () method Tests whether the two URL objects point to the same file. Samefile () execution is very superficial, it is just a relatively opposite fields. SameFile () and equals () have similar things, differences in equals () need to consider all any parameters, while SameFile () does not consider. In addition, any class can be passed to equals (), but only the URL class can be passed to SameFile ().

2) Public string toExternalForm ()

TOEXTERNALFORM () and toString () methods are the same.

Fives. Object method

The URL is inherited from java.lang.object, so all methods of the Object class can be accessed. Similar to the object method of the IentadDress class.

six. Protocol processor method

1) Public static synchronized void seturlstreamHandlerFactory (UrlstreamHandlefactory Factory)

This method sets URLStreamHandleFactory for the application. If the class library has been set, this method triggers a universal error.

2) Public void set (String Protocol, String Host, Int Port, String Authority, String UserInfo, String Path, String Query, String Ref)

Seven. Urlencoder and URLDECoder class

The java.net.urlencoder class contains a single static method called Encode ()

Public Static String Encode (String S)

Urlencoder.Encoder () converts any non-text numeric characters (except spaces, underscores, linked font size, starting, and asterisk), and spaces are converted to plus.

The main purpose of Urlencoder is to prepare a query string for communication using GET's CGI program.

The URLDecoder class puts all the plus transition bit spaces, converts all the percent symbols into the corresponding characters. Public Static String Decode (String S) THROWS EXCEPTION

If the string contains a percent sign, there will be no two hexadecimal numbers, then it will trigger an ILLEGALARGUMENTEXCEPTION. This method passes non-escape characters, so users can pass a complete URL.

转载请注明原文地址:https://www.9cbs.com/read-55624.html

New Post(0)