In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you how to carry out JavaFX HTTP network and XML analysis, the content is very detailed, interested friends can refer to, hope to be helpful to you.
The focus of JavaFX is on the client side, and the aim is to improve the look and feel of Java GUI, thus making the user experience more attractive. Of course, many users' applications need to use remote servers to exchange information. Today, the HTTP protocol and XML are widely accepted as options for interactive information, so what we want to show is how easy it is to handle HTTP communication details in JavaFX, and how we analyze and extract information from an XML data structure.
Basic language concepts of JavaFX
Although it is an assembly language, JavaFX mixes some features of the scripting language inherited from Java. Scripting languages are used for fast and concise application development, while JavaFX is based on the features inherited by Java to make it a more comprehensive language.
JavaFX proposes a new coding model: as a declarative language, it forces us to describe how much we want applications to work without describing specific control flows, even though we do so in the necessary language. This pattern is really powerful when we need to develop GUI. The basic idea is that behind the JavaFX GUI development model is what you want to "describe" what your user interface looks like. In the code and "visual structure." There is a strict relationship between them. In addition, in the code, the commands used to declare objects reflect the commands used to represent them. The overall result is that it is a concise way to create a GUI in just a few lines of code. This makes the application easy to understand and maintain.
Another interesting feature of JavaFX is that it is a statically typed language, which means that the data type, function, and so on of each variable is called compile-time. JavaFX tutorials for this feature can be linked to Resources section.
JavaFX HTTP & XML Package Overview
To develop an application using the HTTP protocol and XML, JavaFX provides some packages, as follows:
Javafx.io.http for handling HTTP communication
Javafx.data.pull and javafx.data.xml for XML parsing
The diagram in Figure1 shows the categories that include these packages:
HTTP & JavaFX
When dealing with the HTTP protocol, we can use the HttpRequest category in the javafx.io.http package. This category enables asynchronous HTTP requests to reach a remote server that supports the HTTP protocol. Currently, HTTP methods are supported:
GET
POST
PUT
DELETE
This category is neutral in data exchange, so we can call a remote server and send any type of information we want to send, as long as we can provide an OutputStream that includes data that must be sent using POST or PUT HTTP methods.
HttpRequest operations related to each HTTP support method have a specific cycle. In the case of the HTTP GET approach, we focus on the cycle. For other methods (POST, PUT, DELETE), the cycle is the same. In the case of a HTTP GET request, the cycle is shown in Figure 2:
Figure 2: HTTP GET method request lifecycle
As we have seen above, the description of each cycle is defined by a specific value of the internal variable of the HttpRequest class.
With regard to the transformation of each variable, there is a corresponding method called during the transition itself, so that we can control and handle different states in the HTTP cycle. These methods all have the same name of the corresponding variable, prefixed with on. For example, if we want to trace a request to connect to the server, we use the onConnecting function.
It's time to code our JavaFX client. First we must declare a variable that includes URL:
Def url: String = "http://www.java.net";
Then create the HTTP request and specify the callback function, which can be called when the HTTP request starts to connect.
HttpRequest {location: url
OnConnecting: function () {
Java.lang.System.out.println ("Connecting")
}
}. Enqueue ()
Notice the method enqueue () that generates the request. Now we want to read the response part. We can use InputStream provided by the onInput function. We need to add this code to the client.
OnInput: function (is: InputStream) {try {
Var responseSize: Integer = is.available ()
Java.lang.System.out.println ("Response size {responseSize}")
}
Finally {
Is.close ()
}
}
The * step is to handle any exceptions that occur during the HTTP request. HTTPRequest has a feature called whenever an exception occurs whenever an exception occurs. So we can add exception handling code to the client.
OnException: function (ex: Exception) {System.out.println ("Error: {ex.getMessage ()}")
}
If you run the client with NetBeans, you can see output similar to Figure 3:
Figure 3: Client log
In the javafx.io.http package, there are two other categories called HttpHeaders and HttpStatus. * categories define a set of constants that correspond to the corresponding HTTP header value names. The second category defines a set of constants that correspond to possible HTTP response codes.
XML API
As we said, many clients today use a XML template to send data to HTTP, and JavaFX provides the ability to simply parse XML files. Now let's focus on the other two packages, as shown in Figure1:
Javafx.data.xml
Javafx.data.pull
Javafx.data.pull contains categories for parsing an XML file, while the javafx.data.xml package defines some constants and handles qualified names. The processor is event-based (similar to SAX parser) and supports two different data formats:
XML
JSON
In this article we focus on the XML data format.
PullParser class is the core of JavaFX's file parser and accepts many of the properties used to control the parser. First, we need to declare a file type that we want to analyze, using the category attribute documentType. The string has two values:
PullParser.XML is used to analyze XML
PullParser.JSON is used to analyze JSON
After declaring the file type, we need to provide file input for analysis. The parser accepts an input stream, which, as we will see later, is very convenient when we need to analyze an XML file from a HTTP request. To declare the input stream, we need to set the value of the input variable.
An example of creating a PullParser is as follows:
Parser = PullParser {documentType: PullParser.XML
Input: xmlFileInputStream
}
When the parser parses the file, it produces a series of entries. We need to execute a callback function to deal with the occurrence of these items. This callback function is called onEvent, and it is in itself, and later we will execute our logic to extract information from the file. The function signature is onEvent (event: Event), and the Event category belongs to the javafx.data.pull package. This category includes all the entries about pull-parsing, and you can use it to extract the information we need. As one of the values in the PullParser definition, Type declares the type of entry, and we are interested in the following types of entries:
START_DOCUMENT: this entry is generated at the beginning of file analysis.
START_ELEMENT: this entry is generated when the parser finds a new starting element. We can use this entry to read element attributes.
END_ELEMENT: this entry is generated when the parser finds the element of *. We can use it to read the text in the element.
END_DOCUMENT: this entry is generated when the parser arrives at the * * file.
There are other entries for the JSON file; if you are interested, take a look at the PullParser file. In any case, there is a framework implementation for responses to START_ELEMENT and END_ELEMENT entries:
OnEvent: function (event: Event) {/ * We start analyzing the different event types * /
If (event.type = = PullParser.START_ELEMENT) {
/ * Here we implement our logic to handle the start element event
For example to extract the attribute values and so on * /
}
Else if (event.type = = PullParser.END_ELEMENT) {
/ * Here we implement our logic to handle the end element * /
}
}
In the process of analysis, some errors will also occur. We can manage them as long as we check the type of item generated by the parser. Integrate HTTP & XML APIs
Now that we have described these two API, it's time to take a look at the most interesting part: how do we integrate everything so that we can compile a complete XML-over-HTTP client. This is very useful if we want a client to exchange information with a remote server.
Let's assume that the JavaFX client application invokes a serlet structure that can recover XML files as follows:
xml version= "1.0" encoding=" UTF-8 "? >
< data >
< person id= "1" >
< name > Mikey < / name >
< surname > Mouse < / surname >
< / person >
< / data >
This is a simple XML file, but enough to achieve the purpose of the example. Our goal is to connect to the test serlet for our client and retrieve the XML content, then analyze it and display the extracted information. To do this, we need to change the HttpRequest function onInput so that we can also parse the XML file when we start receiving it. The code for how to do this is as follows:
OnInput: function (is: InputStream) {try {
PullParser {
Input: is
OnEvent: function (event: Event) {
/ / We handle the event
}
}. Parse ()
}
Finally {
Is.close ()
}
}
Notice how we added PullParser to the onInput function, and we set the parser input stream to the input stream received from HttpRequest. Now we only need to deal with the entries described above:
.... If (event.type = = PullParser.START_ELEMENT and event.level = = 1) {
Java.lang.System.out.println ("Start a new element {event.qname.name}")
Var qAttr: QName = QName {name: "id"}
Var attVal: String = event.getAttributeValue (qAttr)
Java.lang.System.out.println ("Attribute ID value {attVal}")
}
Else if (event.type = = PullParser.END_ELEMENT) {
Var nodeName: String = event.qname.name
Java.lang.System.out.println ("End element {nodeName}")
/ / Now we extract the text only if the node is name or surname
If (nodeName = = "name" or nodeName = = "surname") {
Var textVal: String = event.text
Java.lang.System.out.println ("Text {textVal}")
}
}
....
It is very useful to analyze the code step by step. In the case of a PullParser.START_ELEMENT entry, we use the event.level variable. This tells us on which line each entry occurs (starting at 0, the root of the XML file). We already know that the id attribute is on the * line, so we only restrict extraction on this line. Then create a QName target setting, the name changes according to the attribute name, and then we apply the value.
In the case of PullParser.END_ELEMENT, we want to extract the node content. To do this, we use the text variable that includes the node value.
If everything works well, we will see the analyzed entries in the project console (console), such as Figure 4. 0. As shown:
Figure 4. HTTP request with XML parsing
Concluding remarks
In this article, we explore some of the basic features of JavaFX, focusing on two important aspects: XML and HTTP. We found it easy to develop a client for HTTP requests and XML responses. This is a simple example, but it can be extended by adding other features, such as connecting to a site or retrieving images.
On how to carry out JavaFX HTTP network and XML analysis to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.