Java high-level network programming

zhaozj2021-02-17  83

Java high-level network programming

Qusay H. Mahmoud 2002-11-14 Border madman translation 2002-12-10

HTTP-based application

The classes and interfaces in the Java.NET package provide APIs available for low-level and high-level network programming. The low-level API allows you to access the network protocol directly, but you have to use low-level TCP sockets and UDP packets. High-level APIs (such as URL, URLCONNECTION and HTTPURLCONNECONNECTION, etc.) can make you more quickly develop web applications, but don't need to write a lot of code.

Another article, "NetWork Programming With J2se 1.4" will tell you how to use the low-level socket for network programming. The focus of this article is placed on how to develop HTTP-based applications in the high-level API in the Java.NET package.

This article will have the following:

Overview HTTP Overview Java.NET Package High-level API Example shows how to make an application for downloading stock markets to demonstrate how to submit data to web server overview HTTP authentication and show how to protect your network resource information instance presentation how to execute HTTP verification

Overview http

Hypertext Transfer Protocol, HTTP is a "request-response" application protocol. This protocol supports a fixed method such as GET, POST, PUT, DELETE, and so on. The GET method is generally requested to request resources to the server. Here are two examples of GET requests:

Get / http / 1.1

Get /Names.html http / 1.1

Alternatively, you can send data to the server using the GET and POST methods, which are different from the way data to the server:

GET method: The input data will send a POST method as part of the URL: Enter data as a separate entity

Consider the following HTML form:

STUDENT #:

This form will be submitted to http://www.javacourses.com/servlet/getmarks Processed by servlet. This form uses the GET method to transfer information. If the user enters a student number-such as 556677 - and click the GetMarks button, the form data will be sent to the servlet as part of the URL. After encoding, the URL is: http://www.javacourses.com/servlets/getmarks? Number = 556677.

In the case of using the POST method, the data does not use the data as part of the URL when transmitting data; they are transmitted as a separate entity. Therefore, the Post method is safer, you can also use this method to transfer more data. Moreover, the data transmitted by POST does not necessarily want to be text, but it is necessary to use the GET method to be text.

Message format

Request Message Specifies the method name (GET or POST), URL, protocol version number, header message, and optional messages. Head messages may contain request information and client information, such as acceptable content types, browser names, and verification data. The return message specifies the protocol version, response code, and reasons. Regardless of whether it is successful, response code and reasons will be reported. Some response code is as follows:

.

400 Bad Request: Request Message Is Not Understood by The Server.

404 NOT Found: Requested Document Is Not Found On this Server.

Information about HTTP and all returned code can be found in the HTTP 1.1 specification RFC2616.

Below is an example of a request message by a browser to the server. The URL of the requested here is http://java.sun.com:

Get / http / 1.1

Accept: Image / GIF, Image / X-Xbitmap, Image / JPEG, Image / PJPEG,

Application / VND.ms-PowerPoint, Application / VND.MS-Excel,

Application / MSWORD, * / *

Accept-language: EN-CA

Accept-encoding: Gzip, deflate

User-agent: mozilla / 4.0 (compatible; msie 5.01; windows 98; ycomp 5.0.0.0)

Host: java.sun.com

Connection: Keep-alive

Cookie: sun_id = 24.80.19.177: 28346100732290;

Sunoneuserid = 24.80.19.177: 86521021960770

Then here is the server's reply message for this request:

HTTP / 1.1 200 ok

Server: Netscape-Enterprise / 6.0

Date: Mon, 14 Oct 2002 15:18:04 GMT

Content-Type: Text / HTML

Connection: Close

Overview of the high-rise API of the java.net package

The java.net package contains a high-level API. They achieve some most commonly used TCP-based protocols such as HTTP and FTP, etc. Two of these major classes are URL and URLConnection. Another useful class is httpurlconnection, which is the subclass of URLConnection, supports the characteristics of HTTP.

URL (Uniform Resource Locator, Uniform Resource Locator) is an address that describes documents (or other common resources) in the Internet. The URL look like this:

Protocol: // Machinename: Port / Resource

Note that the URL class is not based on HTTP, this is very important. It supports FTP, HTTPS, and FILE protocols. Therefore, for the URL class, all URLs below are valid.

http://java.sun.com

http: // localhost: 8080 / myapplication

http://www.yahoo.com/index.html

http://www.yahoo.com

ftp://ftp.borland.com

ftp://ftp.sun.com

https://www.scotiaonline.scotiabank.com

https://central.sun.net

File: /// c: /j2sdk1.4/docs/api/index.html

When you enter a URL in your browser, the browser generates an HTTP GET (or POST) command to find (or query) the resources requested by the URL. If you do not specify the resources you want to query, the query will be the default document (usually index.html). Read the content of the URL

Let us start with a simple app, it will read the content directly from the URL. Try to read the low-level socket to read, see the sample code 1. In this example, the user enters the URL of the command line and then opens a socket on the 80-port (the default HTTP server port number) and establishes the corresponding input and output stream. The output flows to send http commands to the HTTP server (such as GET), and the input stream is used to read the return of the HTTP server. Note that in this example, the header information of the server will be read (this is something other than the URL content).

Sample Code 1: Readurl1.java

Import java.net. *;

Import java.io. *;

Public class readurl1 {

Public static void main (string argv []) throws exception {

Final Int http_port = 80;

IF (argv.length! = 1) {

System.out.println ("USAGE: Java Readurl1 );

System.exit (0);

}

Socket Socket = New Socket (Argv [0], http_port);

BufferedWriter Out

= New buffsetwriter (new output.getstreamwriter);

BufferedReader in

= New BufferedReader (New InputStreamReader (Socket.getInputStream ()));

Out.write ("Get / IndEx.html HTTP / 1.0 / N / N");

Out.flush ();

String line;

StringBuffer SB = new stringbuffer ();

While ((line = IN.Readline ())! = null) {

Sb.append (line);

}

Out.close ();

In.Close ();

System.out.println (sb.toString ());

}

}

// end code

When you run this example, please note that the URL must be a domain name such as java.sun.com or IP address. You cannot add http: // as part of the URL. If you have to solve this problem, you have to parse the input content and find out what protocol, port number, and what resources are requested. You can also use URL classes, which offer some very useful methods such as getProtocal, getport, gethost, and getfile.

Use URL class

To read content from the URL, you can use the URL class to be very easy to implement, just as shown in the sample code 2. This makes it easy to read the content directly from the URL. The content read by this method does not contain the header information responded to the server, so it doesn't need you to parse them. When you run this example, enter a valid URL, just like protocol: // DomainName: Port / Resource. The URL class analyzes the input URL and processes the work of low-level troubles.

Sample Code 2: Readurl2.java

Import java.net. *;

Import java.io. *;

Public class readurl2 {public static void main (string argv []) throws exception {

IF (argv.length! = 1) {

System.out.println ("USAGE: Java Readurl2 );

System.exit (0);

}

URL URL = New URL (Argv [0]);

BufferedReader in

= New BufferedReader (Url.OpenStream ());

String line;

StringBuffer SB = new stringbuffer ();

While ((line = IN.Readline ())! = null) {

Sb.append (line);

}

In.Close ();

System.out.println (sb.toString ());

}

}

When you run Readurl2, you will see the document content command window requested by the URL you entered.

If you want to do other things other than reading, use OpenConnection to create a connection to the URL. This method returns a URLCONNECTION object, you can use this object to communicate with the URL, such as reading, writing, query, etc. One, the OpenConnenEtion method creates a connection, you can use GetContentType, getContentLength, getContenTencoding, etc. very useful methods.

Use the URLConnection class

We now have to create a application from http://quote.yahoo.com to demonstrate how to use URLConnection. In order to obtain special stock information, the user enters stock labels (such as sunw, IBM or MOT), and obtains the corresponding stock information from the Yahoo Quote server. The app shows the name, price and date of the stock.

There are two ways (can be used in this application) to get stock information from the Yahoo Quote server. The format of the first method is as follows:

http://quote.yahoo.com/d/quotes.csv?s=sunw&f=slc1wop

If you enter this URL in the address bar of the browser, you will see those shown in Figure 1.

Figure 1: Get stock market

Another format of another method is:

http://finance.yahoo.com/q?s=sunw

Figure 2: Another way to get the stock market

You can see the result of the first method is a line of text. It will be much easier than the second, which is much faster, because the results of the second method contain a lot of text, including many advertisements and formatted information. So I use the first way to implement this application of stocks, which consists of two classes: stock. Java and stockReader.java.

Stock. Java class

This class will resolve the string from the Yahoo Quote server to field (such as stock name, price, and date). An example of an implementation is shown in the sample code 3. The STOCKREADER class in Sample Code 4 will use this tool class.

Sample code 3: stock.java

Public class stock {

Private static string name, time, price;

// given a quote from the server,

// Retrieve The Name, Price, And Date of The Stock

Public Static Void Parse (String Data) {INDEX = DATA.INDEXOF ('");

Name = data.substring ( index, (index = data.indexof ('", index));

INDEX = 3;

Time = data.substring (Index, (INDEX = DATA.INDEXOF ('-', index)) - 1);

INDEX = 5;

Price = data.substring (index, (index = data.indexof ('>', index));

}

// Get the name of the stock from

Public static string getname (string record) {

PARSE (RECORD);

Return (Name);

}

// Get the price of the stock from

Public static string getprice (string record) {

PARSE (RECORD);

Return (Price);

}

// Get the date of the stock

Public static string getdate (String Record) {

PARSE (RECORD) ;;

Return Time;

}

}

StockReader.java class

This type of task is to connect to the Yahoo Quote server and get a stock market from the server. It uses the STOCK class to resolve the string returned from the server. Example Code 4 is an implementation thereof.

Sample code 4: stockReader.java

Import java.io. *;

Import java.net. *;

Public class stockReader {

Public static void main (string argv []) throws exception {

String quoteformat = "& f = slc1wop";

IF (argv.length! = 1) {

System.err.Println ("Usage: Java stockReader ");

System.exit (1);

}

URL URL = New url ("http://quote.yahoo.com/d/quotes.csv?");

UrlConnection Connection = Url.openConnection ();

Connection.SetDoOutput (TRUE);

PrintWriter out = new printwriter (connection.getoutputstream ());

Out.println ("s =" argv [0] quoteformat);

Out.close ();

BufferedReader in = New BufferedReader

New INPUTSTREAMReader (Connection.getInputStream ()));

String line = in.readline ();

/ * Debug

While ((line = IN.Readline ())! = null) {

System.out.println ("Got:" line);

}

* /

In.close (); System.out.Println ("Name:" stock.getname (line);

System.out.println ("Price:" stock.getprice (line);

System.out.println ("Date:" stock.getdate (line);

}

}

Submit data to web server

In the above example, the data is sent as part of the URL to the server, and the used GET method is used. Now let's take a look at an example of sending data using the Post method. In this example, the CGI script in http://www.javacours.com/cgi-bin (named .cgi) requires Name and Email values. If the user submits Sally McDonald as a Name value, SMC @ Yahoo.com acts as an email value, the CGI script will get the input and parse, decode the message, and then return the submitted content to the client. This CGI script is not much, but we have to use it to demonstrate how to submit data to the server.

There is also a very important thing - please note that the type of message content is Application / X-WWW-Form-Urlencoded when using the POST method. This type will:

Specifying a regular data encoding to convert a space to a plus number ( ) to convert the non-text content into a hexadecimal number after the percentage (%) is placed between each Name = Value pair.

According to this coding rule, the message must be encoded before sending to the CGI script is sent:

Name =Sally mcdonald&email=smc@yahoo.com

The CGI script will decode it after receiving this encoded message. But very lucky, you don't have to coding manually. You can use the Java.Net.urlenCoder class to encode the message, just like the following example. Accordingly, you can use java.net.urldecoder to decode the message.

Example Code 5 is an implementation of this example (using the HTTPURLCONNECTION class), which shows how to send data to the server using the POST method. you will see:

Open the connection and I / O stream setting request method for the CGI script to encode the message using the URLEncoder.Encode method (URLDECoder.Decode method can be used to decode) Send a message returned by the encoded message to the CGI script and is controlled Taiwan prints out

Sample code 5: postexample.java

Import java.io. *;

Import java.net. *;

Public class postexample {

Public static void main (string [] argv) throws exception {

URL URL = New URL ("http://www.javacourses.com/cgi-bin/names.cgi");

HTTPURLCONNECTION CONNECTION = (httpurlconnection) URL.OpenConnection ();

Connection.SetRequestMethod ("post");

Connection.SetDoOutput (TRUE);

PrintWriter out = new printwriter (connection.getoutputstream ());

// encode the messageString name = "name =" urlencoder.encode ("Qusay Mahmoud", "UTF-8");

String email = "email =" urlencoder.Encode ("qmahmoud@javacourses.com", "UTF-8");

// send the Encode Message

Out.println (Name & " email);

Out.close ();

BufferedReader in

= New BufferedReader (New INPUTSTREAMREADER ());

String line;

While ((line = IN.Readline ())! = null) {

System.out.println (line);

}

In.Close ();

}

}

Proxy server and firewall

If you use a firewall, you have to tell Java's details of the proxy server and port number, so that you can access the host outside the firewall. You can do it by defining some HTTP or FTP properties:

Http.Proxyhost (Default:

)

Http.Proxyport (Default: 80 if http.proxyhost specified)

HTTP.NONPROXYHOSTS (Default:

)

Http.ProxyHost and http.proxyport are used to specify the proxy server and port number you need to use by the HTTP protocol processor. HTTP.NONPROXYHOSTS is used to specify which hosts are directly connected (ie, not connected by proxy servers). The value of the http.nonproxyhosts property is a list of spaced hosts, which can use regular expressions to represent the matching host, such as: *. sfbay.sun.com will match any host in the SFBay domain.

ftp.Proxyhost (Default:

)

ftp.proxyport (Default: 80 if ftp.proxyhost specified)

FTP.NONPROXYHOSTS (Default:

)

FTP.ProxyHost and Ftp.Proxyport are used to specify the proxy server and port number that the FTP protocol processor needs to use. FTP.nonProxyHosts is used to specify which hosts are directly related, the specified method is similar to http.nonproxyhosts.

You can set these properties when the application starts:

Prompt> java -dhttp.proxyhost = hostname -dhttp.proxyport = portnumber yourapp

HTTP verification

The HTTP protocol provides a verification mechanism to protect resources. When a request requires a protected resource, the web server responds to a 401 unauthorized error error code. This response contains WWW-Authenticate header information specified in the verification method and the domain. This area is imagined into a database stored with usernames and passwords, which will be used to identify valid users of protected resources. For example, you tried to access the resources identified as "Personal Files" on a website, the server response may be: www-automate: Basic realm = "Personal Files" (assuming the verification method is BASIC).

Authentication method

There are now several authentication methods for web applications, where the most widely used is Basic Authentication and Digest Authentication. When the user wants to access a limited resource, the web server that uses the basic authentication method will require the browser to display a dialog and ask the user to enter the username and password. If the username and password entered by the user are correct, the server allows him to access these resources; otherwise, an error message page is displayed after the attempt is fails three times. The disadvantage of this method is that the username and password are transmitted after using Base64 encoding (all readable text). That is, this authentication method is just like Telnet, is not very safe.

The data authentication method does not transmit passwords in the network, but generates some numbers (depending on the password and other data) instead of the password, and these numbers are encrypted by MD5 (Message Digest Algorithm). The generated value is transmitted along with the server if the server needs to use other information to school. This method is significantly more secure.

Based on the form of verification methods and basic verification methods, just the server uses your custom login page to replace the standard login dialog.

Finally, customer certificate verification uses SLL (Secure Socket Layer, Security Sockets) and customer prove.

Protection resources under Tomcat

You can write a list of users and their roles in the Tomcat-Users.xml file. This file is in the Conf directory under Tomcat_home (you install Tomcat's directory). This file defaults to three users (Tomcat, Role1, Both) definitions. One of the XML code below is Tomcat-users.xml after I added two new users (Qusay and Reader):

The newly added two users (Qusay and Reader) are set to Author and Reader, respectively. The role property is very important, because when you create a security rule, each restricted resource is associated with the role that can access it (you will see later).

Let's do an experiment (assuming that you have installed and configure Tomcat). Establish a directory for your expectations. You can prepare it according to the following steps:

In the directory you have installed Tomcat, there is a directory that is WebApps. Create a directory in this directory (such as: Learn). Create a subdirectory in the directory established in the first step, named Chapter. In the chapter directory, create an HTML file, the content is customized, the file name is index.html. Create a subdirectory called web-infers in the directory established in the first step. Create a file called Web.xml in the web-inf directory, the contents of the file are as follows:

Public "- // Sun microsystems, Inc.//dtd Web Application 2.3 // en"

"http://java.sun.com/dtd/web-app_2_3.dtd">

Learning web programing

Restricted Area

/ chapter / *

Tomcat

author

reader

Basic

Authenticate Yourself

Web.xml configuration description

Web.xml is a file that describes the configuration, which is centrally illustrated in the security-related configuration elements.

: This element limits access to one or more resources, can appear multiple times in configuration information. In the above configuration information, it limits all resources accesses under the chapter directory (http:// localhost: 8080 / learn / chapter). contains the following elements:

: This element is used to identify the resources you want to restrict access. You can define the URL mode and HTTP method (define the HTTP method with element). If the HTTP method is not defined, the limit will be applied to all methods. In the above applications, I want to limit the resource for access is http: // localhost: 8080 / learn / chapter / *, that is, all documents in the chapter directory. : This element can access the user role of the restricted resource defined above. In the above application, Tomcat, Author and Erader These resources can be accessed. : This element is used to specify the verification method. It contains the following elements: : Specify the verification method. Its value may be one of the following values: BASIC (Basic Verification), Digest, Form (Form-based Verification) or Client-Cert (Customer Certificate Verification). : When the BASIC method is selected, a description name in the Standard Login dialog box is selected.

Example

The BASIC verification method is used in the above configuration. Below we are experiment: start your Tomcat server and send it to it to the request of 8080 / Learn / Chapter. At this time, there will be a dialog box like Figure 3 prompts you to enter the user and password:

Figure 3: HTTP Basic Verification (Basic Authentication)

Enter a user and its password (you can look at the tomcat-user.xml file), the role of this user should exist in the configuration (web.xml). If the username and password you entered are correct, you can access those resources; otherwise, you can also try twice.

Use a summary verification to experiment:

Close your Tomcat server. Modify your profile (web.xml) and change the BASIC to Digest. Restart your Tomcat server. Open a new browser window. Enter http: // localhost: 8080 / Learn / Chapter in the address bar and enter.

You will see a similar dialog. From Figure 4 you can see that this login dialog is secure because the summary verification is used.

Figure 4: HTTP Summary Verification (Digest Authentication)

Server reply behind the scene

When using basic verification methods to protect resources, the server sent back to the response information similar to Figure 5:

Figure 5: Server Reply (Basic Verification)

If it is used, the resource sent by the server is protected, the response information sent back by the server is like Figure 6:

Figure 6: Server Reply (Summary Verification)

Java supports HTTP verification

J2SE (1.2 or higher) provides local support with the Authenticator class to verify. What you have to do is inherit this class and implement its getPasswordAuthentication method. This method gets username and password and uses them to generate a passwordAuthentication object. After completing, you have to register your Authenticator instance using the Authenticator.SetDefault method. Now, as long as you want to access protected resources, you will call GetPasswordAuthentication. Authenticator class manages all low-level details. It is not subject to HTTP, which can be applied to all network connections, which can't be said to be a good news.

Example Code 6 is an example of implementing Authenticator. As you can see, when requesting verification, getPasswordAuthentication method will pop up a login dialog. Sample Code 6: Authimpl.java

Import java.net. *;

Import java.awt. *;

Import javax.swing. *;

Public class authimpl extends automator {

Protected passwordAuthentication getPasswordAuthentication () {

Jtextfield UserName = New JtextField ();

JtextField Password = new jpasswordfield ();

JPanel Panel = New JPANel (New GridLayout (2, 2));

Panel.add (New Jlabel ("User Name");

Panel.Add (username);

Panel.Add (New Jlabel ("Password"));

Panel.add (Password);

Int Option

= JOPTIONPANE.SHOWCONFIRMDIALOG (NULL,

New Object [] {

"Site:" getRequestingHost (),

"Realm:" getRequestingPrompt (),

Panel},

Enter Network Password,

JOPTIONPANE.OK_CANCANCEL_OPTION,

JOPTIONPANE.PLAIN_MESSAGE);

IF (option == joptionpane.ok_option) {

String user = usrname.gettext ();

Char pass [] = password.gettext (). Tochararray ();

Return New PasswordAuthentication (User, Pass);

} else {

Return NULL;

}

}

}

Sample code 7 is used to do a test. The first thing I did is to start running my Authenticator instance with AuthenTicator.SetDefault. I don't have to resolve any information returned by the server to check if it needs to be verified, because the Authenticator class is very smart, it knows whether it needs to be verified.

Sample code 7: BasicReader.java

Import java.io. *;

Import java.net. *;

Public class BasicReader {

Public static void main (string argv []) throws exception {

Authenticator.SetDefault (New Authimpl ());

IF (argv.length! = 1) {

System.err.Println ("USAGE: Java BasicReader );

System.exit (1);

}

URL URL = New URL (Argv [0]);

UrlConnection Connection = Url.openConnection ();

BufferedReader in

= New BufferedReader (New INPUTSTREAMREADER ());

String line;

StringBuffer SB = new stringbuffer (); while ((line = in.readline ())! = Null) {

Sb.append (line);

}

In.Close ();

System.out.println (sb.toString ());

System.exit (0);

}

}

Run the following command, use Tomcat to test:

Prompt> Java BasicReader http: // localhost: 8080 / Learn / Chapter

If you enter the site needs to be verified (it is also done), it will be displayed like the dialog box like Figure 7.

Figure 7: Java processing HTTP verification

Once you have entered the correct username and password, the server will allow you to access. BasicReader reads the HTML content of the requested page and displayed in your console window.

Special Note: You may encounter problems when using a summary verification in Tomcat 4.0, which is caused by a bug of J2SE 1.4.0 and J2SE 1.4.1. However, this problem has been solved in J2SE 1.4.2. Details

Here.

to sum up

This article is a tutorial that introduces the high-rise API of the Java.net package. These APIs enable you to quickly and more simply create useful web applications, such as stockReader. HTTP verification is also discussed here, and uses examples to demonstrate how to use your own verification solution. There are still some advantages of URL and URLConnection that are not mentioned in the article, including: automatic redirect, automatic management, and the like. But now you have got basic knowledge from the text, you can solve these problems.

(Published in Computer World Knowledge Center)

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

New Post(0)