Java high-rise network programming (GET, POST acquired data)

xiaoxiao2021-03-05  24

Java high-level network programming

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 of the high-rise API of the java.net package

· Example shows how to use high-rise API

· Make a application that can download stock market

· Demonstrate how to submit data to web servers

· Overview HTTP verification and demonstrate how to protect your network resources

· Provide code instance demonstrate how to perform 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 be sent as part of the URL

· POST method: Enter data as an independent 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:

200 OK: Request succeeded The requested resource can be found later in this message 301 Moved Permanently:... Requested resource has moved New location is specified later in this message 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 returns 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.1accept: image / gif, image / x-xbitmap, image / jpeg, image / pjpeg, application / vnd.ms-powerPoint, Application / VND.ms-Excel, Application / MSWORD, * / * Accept- language: en-caAccept-Encoding: gzip, deflateUser-Agent: Mozilla / 4.0 (compatible; MSIE 5.01; Windows 98; YComp 5.0.0.0) Host: java.sun.comConnection: Keep-AliveCookie: 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 OKServer: Netscape-Enterprise / 6.0date: Mon, 14 Oct 2002 15:18:04 Gmtcontent-Type: Text / HTMLConnection: 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 BufferedWriter (new OutputStreamWriter (socket.getOutputStream () ))); Bufferedreader in = new buffredreader (new input.getinputStream ()); out.write ("get / int / denex.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 (new InputStreamReader (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 stockpublic static void parse (String data) {int 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 FROMPUBLIC STATIC STRING GETNAME (STRING RECORD) {Parse (Record);} // Get The Price (String Record) {Parse (RECORD); RETURN (Price);} // Get the date of the stockpublic static string getdate (string record) {parse; 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 (); / * DEBUGwhile (! (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:

· Specify regular data encoding

· Convert space to plus sign ( )

· Convert non-text content into the form of a hexadecimal number (%)

· Place & symbols 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 connection and I / O stream for CGI scripts

· Setting the request method for POST

· Use the Urlencoder.Encode method to encode the message (Urldecoder.Decode method can be used to decode)

· Send a message that has been encoded to the CGI script

· Receive the message returned by the server and print it out at the console

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 encoded messageout.println (name " & " email); out.close (); BufferedReader in = new BufferedReader (new InputStreamReader (connection.getInputStream ())); 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 network applications, where the most widely used is Basic Authentication and Summary Verification (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:

1. In the directory you have installed Tomcat, there is a directory that is WebApps. Create a directory in this directory (such as: Learn).

2. Create a subdirectory in the directory established in the first step, named Chapter.

3. In the chapter directory, create an HTML file, the content is customized, the file name is index.html.

4. Create a subdirectory called Web-INF in the directory established in the first step.

5. Create a file called Web.xml in the web-inf directory, which is as follows:

6. 7. 8. 11.11. 12. 13. 14. 15. Learning web programming16. 17. 18. 19. 21. Restricted area22. 23. / chapter / * 24. 25. 26. Tomcat 27. author 28. reader 29. 30. 31. 32. 33. Basic < / auth-method> 34. Authenticate Yourself 35. 36. 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:

o : This element is used to identify resources you want to limit 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.

O : 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:

O : 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). O : When you use a BASIC method, a description name in the Standard Login dialog box.

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 configuration file (web.xml), replace 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 Authenticator {protected PasswordAuthentication getPasswordAuthentication () {JTextField username = new JTextField (); JTextField password = new JPasswordField (); JPanel Panel = new jPanel (New GridLayout); 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_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (option == JOptionPane.OK_OPTION) {String user = username.getText (); char pass [] = password.getText () toCharArray ();. return new PasswordAuthentication (user, pass);} else {RETURN NULL;}}} sample code 7 is used to test the code. 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 {automator.setdefault (new authorfault ()); 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 (connection.getInputStream ())); 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 you need to verify (it also do this), it will be displayed like the dialog box as shown in 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. See here for details.

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.

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

New Post(0)