Java Common network Operations (URL class, InetAddress class, URLConnection Class)

Source: Internet
Author: User

inetaddress**********************
For InetAddress, three methods: Getlocalhost (), Getbyname (), and Getallbyname () can be used to create instances of inetaddress.
 The InetAddress class does not provide a return constructor, so the new () method cannot be used to create its object, but only static methods Getlocalhost (), Getbyname (), getbyaddress () can be called. And so on to generate the essence of the InetAddress class.


1, InetAddress Common methods:
1.inetaddress.getlocalhost () returns only the InetAddress object that symbolizes the local host. (Returns a local address)
The native address is also localhost,127.0.0.1, and these three addresses are one thing.
Example, Inetaddress.getlocalhost ();//lenovo-pc/169.254.193.131

The 2.getByName () method returns a inetaddress that is passed to its host name.
If these methods cannot resolve host names, they throw a unknownhostexception exception.
On the Internet, it is common to use a name to represent multiple machines.
Example, Inetaddress.getbyname ("www.baidu.com");//www.baidu.com/61.135.169.121

3.getAllByName () The factory method returns an array of inetaddresses classes representing all addresses that are decomposed by a special name.
The Getallbyname () method is to return all of its possible inetaddress objects based on the host name, stored in an array.
When a name cannot be broken down into at least one address, it throws a Unknownhostexception exception.

4.getLoopbackAddress () method returns the local loopback address
Example, inetaddress.getloopbackaddress ();//localhost/127.0.0.1

5. See if the port is already in use
Socket socket = new socket (address,port); #address代表主机的IP地址, port represents the port number.
If a socket can be established on a specific port number for that host, the port of that host is used.
example, import java.net.*;

for (int i = n; i < 1024x768; i++) {
try {
SYSTEM.OUT.PRINTLN ("View port" + i);
Socket SKT = new socket ("localhost", i);
SYSTEM.OUT.PRINTLN ("port" + i + "has been used");
}
catch (Unknownhostexception e) {
System.out.println ("Exception occured" + e);
Break
}
catch (IOException e) {
}
}

Add:The two programs on the network realize the exchange of data through a two-way communication connection, one end of this connection is called a socket.
Establish a network communication connection with at least a pair of port numbers (sockets). Socket is the nature of the programming Interface (API), TCP/IP encapsulation, TCP/IP also to provide the interface for programmers to do network development, this is the socket programming interface; HTTP is a sedan that provides a specific form of encapsulation or display data; the socket is the engine, Provides the ability to communicate on the network.


in Java, the classes inside the java.net package are network-programmed, where the Java.net.URL class and the Java.net.URLConection class make it easy for programmers to use URLs to communicate over the Internet.



URL class ******************************

The 1.URL can be divided into the following sections:
Protocol://host:port/path?query#fragment

Example, HTTP://WWW.RUNOOB.COM/INDEX.HTML?LANGUAGE=CN#J2SE
URL parsing:
Protocol for (Protocol): HTTP
Host for (Host:port): www.runoob.com
The port number is (port): 80, the above URL instance does not specify ports because the HTTP protocol default port number is 80.
File path is (path):/index.html
Request parameter (query): LANGUAGE=CN
Anchor position (fragment): J2SE, navigate to the HTML element location in the Web page where the id attribute is J2SE.


Use of the 2.URL class:
Cases
URL url=new url ("Http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");

2.1 Getting the properties of a URL object
Getdefaultport (): Returns the default port number.
GetFile (): Gets the full file name of the resource specified by the URL.
GetHost (): Returns the host name.
GetPath (): Returns the file directory and file name of the specified resource.
Getport (): Returns the port number, which defaults to-1.
Getprotocol (): Returns a String object representing the protocol in the URL.
GETREF (): Returns the HTML document tag in the URL, which is the # sign.
GetUserInfo: Returns the user information.
ToString: Returns the full URL string.
Cases
URL url=new url ("Http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");
System.out.println (Url.getdefaultport ());//80
System.out.println (Url.getfile ());//wp-content/themes/runoob/assets/img/newlogo.png
System.out.println (Url.gethost ());//www.runoob.com
System.out.println (Url.getpath ());///wp-content/themes/runoob/assets/img/newlogo.png
System.out.println (Url.getport ());//-1
System.out.println (Url.getprotocol ());//http
System.out.println (Url.getref ());//null
System.out.println (Url.getuserinfo ());//null
System.out.println (Url.tostring ());//http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png



URLConnection class **********************

The URLConnection class is an abstract class that represents a communication connection between an application and a URL,instances of this class can be used to read and write resources referenced by this URL.

URLConnection allows request data to be sent to the server using Get,post or other HTTP method requests.

There are two ways to access the Internet. One is to use the OpenStream () method of the URL class, and the second is to use the OpenConnection () method to create an object of the URLConnection class.
where Method OpenStream () establishes a connection to the specified URL and returns an object of the InputStream class to read data from this connection.

example, (Simple page crawl) method one: OpenStream ()
URL url=new url ("http://www.cnblogs.com/Downtime/p/7822379.html");
InputStream Conn=url.openstream ();
InputStreamReader read=new InputStreamReader (conn, "Utf-8");
BufferedReader bread=new BufferedReader (read);
while (bread.readline () = null) {
System.out.println (Bread.readline ());
}
conn.close ();

Method Two: URLConnection
URL url=new url ("http://www.cnblogs.com/Downtime/p/7822379.html");
urlconnection conn=url.openconnection ();
InputStream In=conn.getinputstream ();
InputStreamReader read=new InputStreamReader (in, "utf-8");
BufferedReader reader=new BufferedReader (read);
while (reader.readline () = null) {
System.out.println (Reader.readline ());
}
Conn.getinputstream (). Close ();

2. Common methods:
The list of URLConnection methods is as follows:
1. Object getcontent ()
Retrieving URL link content
2. Object getcontent (class[] classes)
Retrieving URL link content
3. String getcontentencoding ()
Returns the header content-encoding field value.
4, int getcontentlength ()
Return header content-length field value
5. String getContentType ()
Return header Content-type field value
6, int getlastmodified ()
Returns the header last-modified field value.
7, Long getexpiration ()
Returns the header Expires field value.
8, Long getifmodifiedsince ()
Returns the Ifmodifiedsince field value of an object.
9. public void Setdoinput (Boolean input)
URL connections can be used for input and/or output. If you intend to use a URL connection for input, set the DOINPUT flag to true, or set to False if you do not intend to use it. The default value is true.
10. public void Setdooutput (Boolean output)
URL connections can be used for input and/or output. If you intend to use a URL connection for output, set the DOOUTPUT flag to true, or set to False if you do not intend to use it. The default value is False.
11, Public InputStream getInputStream () throws IOException
Returns the input stream of the URL used to read the resource
12, public OutputStream Getoutputstream () throws IOException
Returns the output stream of the URL for writing to the resource.
13. Public URL GetURL ()
Returns the URL of the URLConnection object connection

Java Common network Operations (URL class, InetAddress class, URLConnection Class)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.