Vert.x (vertx) sends HTTP/HTTPS requests

Keywords: PHP JSON SSL network Web Development

Vert.x Web Services have two protocols, one is HTTP and the other is HTTP using ssl. There are five ways of requesting, get, post, put, delete, head.For simplicity, the server mainly implements request processing for get and post of HTTP protocol.as follows

 1 @Override
 2 public void start() throws Exception {
 3  
 4     HttpServer server = vertx.createHttpServer();
 5     Router router = Router.router(vertx);
 6  
 7     // Handle get request
 8     router.get("/get").handler(request -> {
 9         String username = request.request().getParam("username");
10         String password = request.request().getParam("password");
11  
12         System.out.println(username + " " + password);
13  
14         request.response().end("get request success");
15     });
16  
17     // Handle post request
18     router.post("/post").handler(request -> {
19         request.request().bodyHandler(body->{
20             System.out.println(body.toJsonObject().toString());
21             JsonObject responseData = new JsonObject()
22                     .put("msg","success");
23             request.response().end(responseData.toString());
24         });
25     });
26  
27     server.requestHandler(router::accept);
28     server.listen(80);
29  
30 }

The code above creates a Web service that listens for/get and/post addresses to process get and post requests, respectively.If you don't understand the above code, you can refer to Create HTTP Service and Web Development-Routing.

Send HTTP GET request

GET requests are very leaky for sensitive information.

 1 @Override
 2 public void start() throws Exception {
 3     // Establish WebClient,For sending HTTP perhaps HTTPS request
 4     WebClient webClient = WebClient.create(vertx);
 5     // with get Method Request Remote Address
 6     webClient.getAbs("http://localhost/get").send(handle -> {
 7         // Processing the results of the response
 8         if (handle.succeeded()) {
 9         // The result here is one HTML Text, printed directly
10         System.out.println(handle.result().bodyAsString());
11         }
12     });
13 }

This is the simplest way to request an HTTP request. In the code above, a WebClient object is created first, which makes it easy to send HTTP requests through the WebClient.Friends may notice that there is an HttpClient in the Core Package provided by Vert.x, which is available through the Vert.x instance

HttpClient httpClient = vertx.createHttpClient();

The HTTPClient interface can also send HTTP requests, but it is relatively low-level. If complex data is included in the request, along with the request header, encapsulating the response results needs to be handled by itself.Therefore, Vert.x provides vertx-web-client support.

The API for the WebClient is very simple, sending GET requests and using getAbs.Abs means absolute address. In addition to absolute address, you can also use domain name + port number + request address with the following code:

1 webClient.get(80, "localhost", "/get").send(handle -> {
2     // Processing the results of the response
3     if (handle.succeeded()) {
4         // The result here is one HTML Text, printed directly
5         System.out.println(handle.result().bodyAsString());
6     }
7 });

The first parameter is the port number, the second parameter is the domain name, and the third parameter is the request address.

Send HTTP Request Header

The HTTP protocol consists of three parts, the request line, the request header and the request body.Generally speaking, it is not recommended to carry data in the body of a GET request, but request header data is available for each request, such as specifying the type of device and operating system using User-Agent.How do we set the request header when we request a remote service? The code is as follows

1 webClient.get(80, "localhost", "/get")
2 .putHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0")
3 .send(handle -> {
4     // Processing the results of the response
5     if (handle.succeeded()) {
6         // The result here is one HTML Text, printed directly
7         System.out.println(handle.result().bodyAsString());
8     }
9 });

Set timeout

HTTP requests are a time-consuming operation and are subject to network and other factors. Many times we want to limit the maximum request time beyond which we can stop processing and set it up via WebClientOptions

 1 @Override
 2 public void start() throws Exception {
 3     // Establish WebClient,For sending HTTP perhaps HTTPS request
 4     WebClientOptions webClientOptions = new WebClientOptions()
 5     .setConnectTimeout(500); // ms
 6     WebClient webClient = WebClient.create(vertx, webClientOptions);
 7     // with get Method Request Remote Address
 8     webClient.getAbs("http://localhost/get").send(handle -> {
 9         // Processing the results of the response
10         if (handle.succeeded()) {
11             // The result here is one HTML Text, printed directly
12             System.out.println(handle.result().bodyAsString());
13         }
14     });
15 }

In addition to setting a timeout, you can also set whether to redirect to a page, certificates for HTTPS, and so on.

Send HTTP GET request with data

In many cases, it is necessary to take some data with you when requesting the server. There are two ways to request data with GET. The first way is to splice parameters directly after the requested URL? Username=xxx&password=xxxx.Another way to add request parameters is through addQueryParam, as shown below

 1 @Override
 2 public void start() throws Exception {
 3     // Establish WebClient,For sending HTTP perhaps HTTPS request
 4     WebClient webClient = WebClient.create(vertx);
 5     // with get Method Request Remote Address
 6     webClient
 7     .getAbs("http://localhost/get")
 8     // Send data this way
 9     .addQueryParam("username", "admin")
10     .addQueryParam("password", "admin123")
11     .send(handle -> {
12         // Processing the results of the response
13         if (handle.succeeded()) {
14             // The result here is one HTML Text, printed directly
15             System.out.println(handle.result().bodyAsString());
16         }
17     });
18 }

The code above sends two parameters to the server, one is username and the other is password.Both parameters are transmitted over the network in clear text, so if you really want to log in, you must not use get.Here we don't need to think about how the server receives these two parameters, as long as the client can guarantee that the parameters can be sent out.

Send POST Request

GET method is used more in browsers, but generally less in service calls. In service calls, POST method is usually chosen. See the POST method request for remote services case below, the code is as follows

 1 @Override
 2 public void start() throws Exception {
 3     // Establish WebClient,For sending HTTP perhaps HTTPS request
 4     WebClient webClient = WebClient.create(vertx);
 5     // with get Method Request Remote Address
 6     webClient.postAbs("http://localhost/post")
 7     .send(handle -> {
 8     // Processing the results of the response
 9     if (handle.succeeded()) {
10         // The result here is one HTML Text, printed directly
11         System.out.println(handle.result().bodyAsString());
12         }
13     });
14 }

POST and GET requests are very similar in API calls. In the code above, only the postAbs method is called. Developers are not concerned about how the underlying communication protocol is encapsulated. getAbs and postAbs are handled differently at the underlying level.

Send POST request with data

Of course, when making service calls, we also need to include some data. For example, if we want to call SMS service, we need to include at least the mobile number and the text message content. Of course, we need some authentication information in the past. After the service provider sends the text message successfully, we need to tell us that it has been accepted successfully, or onlyJust received our request.There are many ways to carry data in POST and there are many different types of data, there are three main types

1. form Form

2. json string

3. xml string

The first data type is the way that front-end and back-end interact frequently, and the second and third are the serialization methods commonly used in service calls.The following code calls the remote service in the form of sending a JSON string:

 1 @Override
 2 public void start() throws Exception {
 3     // Establish WebClient,For sending HTTP perhaps HTTPS request
 4     WebClient webClient = WebClient.create(vertx);
 5 
 6     // Construct the requested data
 7     JsonObject data = new JsonObject()
 8     .put("username", "admin")
 9     .put("password", "admin123");
10 
11     // with get Method Request Remote Address
12     webClient.postAbs("http://localhost/post")
13     .sendJsonObject(data, handle -> {
14         // Processing the results of the response
15         if (handle.succeeded()) {
16             // The result here is one HTML Text, printed directly
17             // handle.result().bodyAsJsonObject() Can be parsed Json data
18             System.out.println(handle.result().bodyAsString());
19         }
20     });
21 }

In the code above, we first created a JsonObject object, which is similar to JsonObject in GSON and fastjson, but feels more powerful than the JsonObject provided by Vert.x, which makes it very convenient to construct a JsonObject string.In addition to JsonObject, of course, Vert.x also provides JsonArray to construct a JSON array.

After you construct a json object, you can pass in the constructed json object through the sendJsonObject method when requesting a remote service. The bottom level of Vert.x will format the json object into a json string for us and send it to the service provider.The service provider receives the following request data:

1 {
2     "username": "admin",
3     "password": "admin123"
4 }

When the server receives the data, it can also use the JsonObject object to convert the string into a json object for easy reading and writing of the data.Of course, after the server receives our data for processing, it also needs to respond to the data to the client. The server can also respond to the json string to the client, and the client can also process the json string.

There are many such cases for reference WeChat Payment Scavenging Interface Document

https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1

Request HTTPS Service

With the HTTP protocol, data transmission is clear text whether it is a get request or a post request, so sensitive information can be exposed through HTTP.Now more and more websites have been upgraded to HTTPS protocol to transmit sensitive information by encryption.

HTTP request security has two simple points: the first is that the data has been tampered with, and the second is that sensitive data has been stolen.The means to solve data tampering is to sign the message, the means to solve data stealing is to encrypt, HTTPS is actually to solve the problem of sensitive information being stolen.

The principles of HTTPS are not discussed here. Interested friends can search for articles on the network. Requesting HTTPS in Vert.x is also very simple. The code is as follows:

 1 @Override
 2 public void start() throws Exception {
 3     // Establish WebClient,For sending HTTP perhaps HTTPS request
 4     WebClient webClient = WebClient.create(vertx);
 5     // with get Method Request Remote Address
 6     webClient.getAbs("https://www.sina.com")
 7     .ssl(true)
 8     .send(handle -> {
 9         // Processing the results of the response
10         if (handle.succeeded()) {
11             // The result here is one HTML Text, printed directly
12             System.out.println(handle.result().bodyAsString());
13         }
14     });
15 }

The code above is the home page where I want to request Sina. As you can see, just call the ssl method and specify true before calling the send method.

Posted by l_kris06 on Sat, 27 Jul 2019 13:49:00 -0700