InetAddress and URLs for Java network programming

Source: Internet
Author: User

A dedicated network development package is available in Java---Java.net,java network programming provides two communication protocols: TCP (Transmission Control Protocol) and UDP (Datagram protocol).

I. IP (Internet Protocol) and InetAddress class

1.IP Introduction

Each computer on the Internet has a unique identity, the IP address, that represents itself.

IP address = Network address + host address

2.InetAddress

This class mainly represents the IP address, there are two sub-classes: inet4address, Inet6address, the former represents IPV4, the latter represents IPV6.

Common methods of the InetAddress class are:

method description
static inetaddress getbyname (String host)
static inetaddress

getlocalhost ()

returns to the local host.
String GetHostName () Gets the host name of this IP address.
boolean isreachable (int timeout) test if the address can be reached.
To test the InetAddress class:
Package org.demo.net;import java.net.inetaddress;/** * Test inetaddress class * @author Oushine */public class Inetaddressdemo { C1/>public static void Main (string[] args) {        try {            //declare and get local InetAddress object            inetaddress iaddress1= Inetaddress.getlocalhost ();            Declares and obtains the remote InetAddress object            inetaddress iaddress2=inetaddress.getbyname ("www.baidu.com");            Obtain the local IP address            System.out.println ("Native IP address is:" +iaddress1.gethostaddress ());            Obtain the remote IP address            System.out.println ("Baidu's IP Address is:" +iaddress2.gethostaddress ());            SYSTEM.OUT.PRINTLN ("This machine can reach:" +iaddress1.isreachable);        } catch (Exception e) {            e.printstacktrace ();}}    }

Results:

Two. URLs and URLConnection

1.URL

The URL (Uniform Resource Locator) is a Uniform resource locator that can be used directly to find resources on the Internet (such as a Web page).

Common methods for URL classes:

Type Method Describe
Construction method

URL(String spec)

Creates an object based on the String representation URL .
Construction method URL(String protocol, String host, int port, String file) protocolThe object is created according to the designation, host port number, and file URL .
URLConnection openConnection() Returns an URLConnection object that represents the connection to the URL referenced remote object.
inputstream

openstream ()

open to this   URL   Connection and returns a   that is used to read from the connection; InputStream .
To read content using a URL:
Package Org.demo.net;import Java.io.inputstream;import Java.net.malformedurlexception;import java.net.URL;import Java.util.scanner;public class Urldemo {public    static void Main (string[] args) {        URL url;        try {            //Specify the URL URL of the action            = new URL ("http", "www.baidu.com", "/index.html");            Open input stream, read URL content            inputstream inputstream=url.openstream ();            Scanner scan=new Scanner (inputstream);            Sets the read delimiter            scan.usedelimiter ("\ n");            while (Scan.hasnext ()) {                //output content                System.out.println (Scan.next ());            }        } catch (Exception e) {            E.printstacktrace ();}}}    

Results:

The HTML code is displayed.

2.URLConnection

URLConnection is a class that encapsulates a general method of accessing remote network resources through which you can establish a connection to a remote server and examine some of the properties of a remote resource.

Common methods:

method description
int

getcontentlength ()

return   content-length   Header field values.
String

getcontenttype ()

return to   Content-type The value of the   header field.
inputstream

getInputStream ()

The URLConnection object can be obtained through the OpenConnection () method of the URL class.

get basic information about the URL:
Package Org.demo.net;import Java.net.url;import Java.net.urlconnection;public class Urlconnectiondemo {public    static void Main (string[] args) {        try {            url url=new url ("http://www.baidu.com");            Establish a connection            urlconnection urlconn=url.openconnection ();            SYSTEM.OUT.PRINTLN ("Content size:" +urlconn.getcontentlength ());            System.out.println ("Content type:" +urlconn.getcontenttype ());        } catch (Exception e) {            e.printstacktrace ();}}    }
Operation Result:

Three. Urlencoder and Urldecoder

In Java, if you need to complete the encoding and decoding operations, you will use Urlencoder and Urldecoder two classes.

Methods of the Urlencoder class:

Type Method Describe
static String encode(String s, String enc) Converts a string to a format using the specified encoding mechanism application/x-www-form-urlencoded .

Methods of the Urldecoder class:

Type Method Describe
static String decode(String s, String enc) Decodes a string using the specified encoding mechanism application/x-www-form-urlencoded .
encoding and decoding operations:
Package Org.demo.net;import Java.net.urldecoder;import Java.net.urlencoder;public class Codedemo {public    static void Main (string[] args) {        String keyword= "Oushine yang";        try {            String encode=urlencoder.encode (KeyWord, "UTF-8");            SYSTEM.OUT.PRINTLN ("After encoding:" +encode);            String Decode=urldecoder.decode (EnCode, "UTF-8");            System.out.println ("After decoding:" +decode);        } catch (Exception e) {            e.printstacktrace ();}}            }

Operation Result:

Transferred from: Https://www.cnblogs.com/yzl-i/p/4442892.html#top

InetAddress and URLs for Java network programming

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.