Fundamentals of Java Network Programming (i)

Source: Internet
Author: User

The Java SDK provides a relatively simple API to complete network functions, which exist in the java.net package, and the network functionality provided by Java can be broadly divided into three categories.

    • Network programming based on HTTP protocol: this is the most advanced of the three major categories of functions. Through the network resource expression of the URL, it is easy to make sure the location of the data on the network. Use URLs and Urlconnection,java programs to read directly into the data placed on the network, or to transfer your own data to the other end of the network

    • Socket programming based on TCP/IP protocol: it can be imagined that two different programs pass through the network channel, and this is the most common method in traditional network programs. Typically client server software in TCP/IP network protocol uses sockets and ServerSocket as a way to interact

    • Socket programming based on UDP protocol: datagram is the lowest of these functions. Other methods of network data transmission are supposed to establish a stable channel when the program executes. When the TV transmits the data in a datagram way, it simply records the destination of the data in the packet and then transmits it directly on the network, and the system does not guarantee that the data will be sent safely or not when it can be delivered.

The above 3 functions, we will be around the 3 types of core to explain

    • HTTP protocol Core class: includes Web address class URL, network connection class URLConnection, HttpURLConnection, jarurlconnection

    • TCP/IP Protocol Core class: includes IP address class inetaddress, client socket socket, server end socket ServerSocket

    • UDP protocol Core class: Includes datagram class Datagramsocket, datagram socket datagrampacket, multicast sockets MulticastSocket

1. Network programming based on HTTP protocol

This section starts with the URL format of the URI and URL, then explains the URLs, URLConnection, and other classes, demonstrating how to read the content of the Web page. The main content includes the following items:

  • Network Address Uri→url

  • URL Web address class

  • URLConnection Web Connection Class

  • HttpURLConnection and Jarurlconnection

URIs, URLs, and urns are standard ways to identify, locate, and name resources on the Internet.

URI: Is the uniform identity of the resource. It identifies a simple string of resources in a uniform way. The URI begins with the schema and colon.

URIs cannot locate or read and write resources, which are the tasks of a Uniform Resource Locator (URL).

A URL is a URI, but its outline component is a known network protocol, and it relates the URI component to a protocol handler

The URL address can include the following forms of information:

  • The default URL format is as follows: Http://www.socs.uts.edu.au/MosaicDocs

usually URLs can be divided into several parts. The above URL example indicates that the protocol used is the HTTP protocol, and that the information resides on a host named www.socs.uts.edu.au. The host's information name is/mosaidocs, and the exact meaning of this name on the host depends on the protocol and host. This information is typically stored in a file, but can be generated at any time
  • The URL can specify a port that is used to establish the port number to the remote host TCP link.

  • An application can also specify a relative URL, which simply contains enough information to reach a resource relative to another URL

Http://java.sum.com/index.html

URL Web address class

The URL is an abbreviation for the uniform Resource Locator (Uniform Resource Locator). The class URL represents a Uniform Resource locator, which is a pointer to an Internet resource.

The URL class gives us a different way to construct

    1. Constructs a URL based on an address. Public URL (String spec);

    2. Create URLs based on protocol, hostname, port, and file. Public URL (String protocol,string host,string port,string file);

    3. The default 80 port is used, based on the protocol, hostname, and file creation URL. Public URL (String protocol,string host,string file);

Creates a URL based on the URL instance. The construction method is used for URL objects that already exist in the context bedstead URL object. Examples are as follows: public URL (url context,string spec);

try{URL base = new url ("url url3 = new URL (base," #change ");} catch (Malformedurlexceptioin e) {e.printstacktrance ();}


Querying URL Object Information

A URL object is created that can manipulate objects using the methods of the class, and some basic methods in the URL class are as follows:

  • Gets the authorization section for this URL: String getauthority ();

  • Gets the contents of this URL: Object getcontent ();

  • Gets the contents of this URL: Object getcontent (class[] classes);

  • Gets the default port number of the protocol associated with this URL: int getdefaultport ();

  • Gets the file name for this URL: String getFile ();

  • Gets the path part of this URL: String getpath ();

  • Gets the port number of this URL: int getport ();

  • Gets the protocol name for this URL: String getprotocol ();

  • Gets the query part of this URL: String getquery ();

  • Get reference: String getRef ();

  • Gets the URL of the userinfo:string getuserinfo ();


URLConnection Web Connection Class

It represents the communication link between the application and the URL. Instances of this class can be used to read and write resources referenced by this URL. Usually a link to a URL usually takes several steps.

(1) Create a linked object by calling the OpenConnection () method at the URL

The URL class OpenConnection () is used to return a URLConnection object that represents the connection to the remote object referenced by the URL, in the following format:

URLConnection OpenConnection ();

(2) Set request parameters and general request parameter properties

Modify the configuration parameters using the following methods:

void Setallowuserinteraction (Boolean allowuserinteraction);//settings Allow user interaction

void Setdoinput (Boolean doinput)//Set input

void Setdooutput (Boolean dooutput)//Set Output

void Setifmodifiedsince (long ifmodifiedsince);//Set the latest access time

void Setusercaches (Boolean usercaches)//whether to enable slow village

(3) using the Connect () method to establish an actual connection to a remote object

Void Connection ();//Open the communication link to the resource referenced by this URL

(4) After establishing a link to the remote object, the method is used to access the header fields and contents:

Object GetContent ();//Gets the contents of this URL link

Some header fields need to be accessed frequently, using the following method:

  • String Getheaderfield (int n);//Returns the value of the nth header field

  • String Getheaderfield (string n AME);//Returns the value of the specified header field

  • String getcontentencoding (); Returns the value of the Content-encoding header field

  • Int Getcontentlength (); Returns the value of the Content-length header field

  • String getcontenttype (); Returns the value of the Content-type header field

  • Long getDate (); Returns the value of the Date header field

Code example

Import Java.io.inputstream;import Java.net.url;import Java.net.urlconnection;public class Testnet {public static void Main (string[] args) {//Demo Urltry {//Create Urlurl URL by address = new URL ("http://www.360doc.com/content/14/0908/10/8358419_ 407786658.shtml ");//Get Urlconnectionurlconnection conn = Url.openconnection ();//Open Connection Conn.connect ();// Get attribute System.out.println (Conn.getcontentlength ()); System.out.println (Conn.getcontenttype ()); System.out.println (Conn.getdate ()); System.out.println (Conn.getexpiration ()); System.out.println (Conn.getlastmodified ());//Get url//read Web page data int E;inputstream is = Conn.getinputstream (); while ((E = Is.read ())! =-1) {System.out.print ((char) e);} Is.close ();} catch (Exception e) {//Todo:handle Exception}}}



This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1774561

Fundamentals of Java Network Programming (i)

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.