Vert.x (vertx) transmitting HTTP / HTTPS requests

 Vert.x Web Services, there are two agreements, one is HTTP, another is the use of ssl HTTPS, request the way there are five, are get, post, put, delete, head. For simplicity, the main server and the request processors to get the post 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     // 处理get请求
 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     // 处理post请求
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 above code is to create a Web service, monitoring / get and / post address, were treated get requests and post requests. If you do not understand the code above friends can refer to the "Create HTTP service" and "Web Development - Routes"

Send an HTTP GET request

GET request for disclosure of sensitive information very easily.

. 1  @Override
 2  public  void Start () throws Exception {
 . 3      // Create WebClient, configured to send HTTP or HTTPS requests 
. 4      the WebClient WebClient = WebClient.create (VertX);
 . 5      // to get the remote address mode request 
. 6      webClient.getAbs ( "HTTP: // localhost / GET") .send (handle -> {
 . 7          // result of the process response 
. 8          IF (handle.succeeded ()) {
 . 9          // here to get the result is an HTML text, direct print out 
10          System.out.println (handle.result () bodyAsString ().);
 . 11          }
 12 is      });
 13 is }

This is the simplest way to request, in the above code, the first WebClient create objects that can send an HTTP request via WebClient. A friend may have noticed, there are HttpClient in the core package Vert.x provided, can be obtained by Vert.x examples

HttpClient httpClient = vertx.createHttpClient();

HTTPClient This interface may also send HTTP requests, but it is relatively low, if the data in the request with the complex, with the first request, the results are encapsulated in response has to handle. Therefore, Vert.x provides support vertx-web-client of.

WebClient The API is very simple, send a GET request, you can use getAbs. It is Abs means an absolute address, except that absolute address, the domain name may be used and port number + mode request address code is as follows:

. 1 webClient.get (80, "localhost", "/get").send(handle -> {
 2      // process the response result 
. 3      IF (handle.succeeded ()) {
 . 4          // results presented here is to get a HTML text, direct print out 
. 5          System.out.println (handle.result () bodyAsString ().);
 . 6      }
 . 7 });

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

Request sends an HTTP request header

HTTP protocol consists of three parts, the request line, request headers and the request body. Generally, the band data is not recommended in the request body GET request, the request header data of each request, such as the type of User-Agent using the specified device and the operating system and the like. When we request remote services, how to set up the first request it, the code is as follows

. 1 webClient.get (80, "localhost", "/ GET" )
 2 .putHeader ( "the User-- Agent", "the Mozilla / 5.0 (the Windows NT 10.0; Win64; x64-; RV: 65.0) the Gecko / Firefox 20,100,101 / 65.0" )
 . 3 .send (handle -> {
 . 4      // result of the process response 
. 5      IF (handle.succeeded ()) {
 . 6          // results presented here is to get a HTML text, the direct print 
. 7          System.out.println (handle . .Result () bodyAsString ());
 . 8      }
 . 9 });

Set the timeout

HTTP requests is a time-consuming operation, affected by factors such as network, many times we want to limit a maximum request time, over this time not to deal with, you can set by WebClientOptions

. 1  @Override
 2  public  void Start () throws Exception {
 . 3      // Create WebClient, configured to send HTTP or HTTPS requests 
. 4      WebClientOptions webClientOptions = new new WebClientOptions ()
 . 5      .setConnectTimeout (500); // MS 
. 6      the WebClient WebClient = WebClient.create (VertX, webClientOptions);
 . 7      // to get the remote address mode request 
. 8      webClient.getAbs ( "HTTP: // localhost / get") .send (handle -> {
 . 9          // result of the processing in response to the 
10          IF (handle.succeeded ()) {
 11              //The result of this is to get a HTML text, direct print out 
12 is              System.out.println (handle.result () bodyAsString ().);
 13 is          }
 14      });
 15 }

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

Sending an HTTP GET request with data

When requesting the service side need to bring a lot of cases the necessary data, GET request with data in two ways, URL parameters directly after splicing is the first request? Username = xxx & password = xxx in the form of. Another way is by adding addQueryParam request parameters, as follows

. 1  @Override
 2  public  void Start () throws Exception {
 . 3      // Create WebClient, configured to send HTTP or HTTPS requests 
. 4      the WebClient WebClient = WebClient.create (VertX);
 . 5      // to get the remote address mode request 
. 6      WebClient
 . 7      .getAbs ( "HTTP: // localhost / GET" )
 . 8      // send data in this way 
. 9      .addQueryParam ( "username", "ADMIN" )
 10      .addQueryParam ( "password", "admin123" )
 . 11      .send (handle - > {
 12          // result of the processing in response to 
13         IF (handle.succeeded ()) {
 14              // results presented here is to get a HTML text, direct print out 
15              System.out.println (handle.result () bodyAsString ().);
 16          }
 . 17      });
 18 is }

The above code is sent to the server two parameters, one is a username is password. These two parameters are transmitted over the network in clear text, so if you really need to do is log in, you must not use the get way. Here we do not need to think about how the server receives these two parameters, as long as the client to ensure that the parameters to be sent out on it.

POST request sent

GET method is used more in the browser, but in general fewer service calls, service calls will generally choose to use the POST method, see POST method request remote services following cases, the code is as follows

. 1  @Override
 2  public  void Start () throws Exception {
 . 3      // Create WebClient, configured to send HTTP or HTTPS requests 
. 4      the WebClient WebClient = WebClient.create (VertX);
 . 5      // to get the remote address mode request 
. 6      webClient.postAbs ( "HTTP: // localhost / POST" )
 . 7      .send (handle -> {
 . 8      // process the response results 
. 9      IF (handle.succeeded ()) {
 10          // here to get the result is an HTML text, direct printing out 
. 11          System.out.println (handle.result () bodyAsString ().);
 12 is          }
 13 is     });
14 }

POST method and GET method request is very similar in API calls, the above code, just call the postAbs method only, the developers how the underlying communication protocol is encapsulated completely without concern, getAbs and postAbs the underlying approach is completely different.

POST request with data transmission

After the course, when the general service call also requires accompanying some of the data, such as we have to call the texting service, then you at least need to be accompanied phone number and content of messages in the past of course, also need some authentication information, the service provider sends an SMS Success requires tell us success has been accepted, or simply receive our request. More in POST mode band data, the data type is also diversified, there are three main types of

1. form form

2. json string

3. xml string

The first data type is frequently used when the front and rear ends of the interaction, a second three way calling service is commonly used in serialization. Below to form a JSON string transmitted to remote service call, as follows:

. 1  @Override
 2  public  void Start () throws Exception {
 . 3      // Create WebClient, configured to send HTTP or HTTPS requests 
. 4      the WebClient WebClient = WebClient.create (VertX);
 . 5  
. 6      // data structure of the request 
. 7      JSONObject Data = new new JSONObject ()
 . 8      .put ( "username", "ADMIN" )
 . 9      .put ( "password", "admin123" );
 10  
. 11      // to get the remote mode request address 
12 is      webClient.postAbs ( "HTTP: // localhost / POST " )
 13 is      .sendJsonObject (Data, handle ->{
 14          // result of the processing in response to the 
15          IF (handle.succeeded ()) {
 16              // results presented here is to get a HTML text, the direct print
 . 17              // handle.result (). BodyAsJsonObject () can parse the data Json 
18 is              System.out.println (handle.result () bodyAsString ().);
 . 19          }
 20 is      });
 21 is }

In the above code, we create a JsonObject objects, and GSON fastjson in JsonObject and the like, but it feels JsonObject Vert.x provide more powerful, it could very easily constructed by a Json string JsonObject. Of course, in addition to JsonObject, Vert.x JsonArray also provides a json array may be constructed.

After a json object is configured, when the request of the remote service by sendJsonObject method, the constructed json incoming objects, will give us the bottom vert.x json json objects formatted as a string, to the service provider. Service providers will receive the requested data as follows:

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

The server receives the data object may also be used JsonObject string to json objects, easy to read and write data. Of course, carried out after the server receives our data processing and, finally, the need to respond to client data, the server can respond to json string to the client, the client can also be processed json string.

This case is very large, you can refer to the micro-channel pay scan code interface documentation

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

HTTPS service request

Using the HTTP protocol, either get or post request request, the data transmission is transmitted in the clear, and therefore the risk of sensitive information over HTTP are exposed. Now more and more sites have been upgraded to HTTPS protocol for transmission over an encrypted manner to ensure the security of sensitive information.

Briefly secure HTTP requests there are two, the first one is tampering with the data, the second sensitive data theft. Means to solve the data tampering is to sign the message, the means to solve the theft of data is encrypted, HTTPS is to actually solve the problem of sensitive information stolen.

For HTTPS principle here is not too much introduction, interested friends can search for articles on the Web, HTTPS request is very simple, as follows in Vert.x in:

. 1  @Override
 2  public  void Start () throws Exception {
 . 3      // Create WebClient, configured to send HTTP or HTTPS requests 
. 4      the WebClient WebClient = WebClient.create (VertX);
 . 5      // to get the remote address mode request 
. 6      webClient.getAbs ( " HTTPS : //www.sina.com" )
 . 7      .ssl ( to true )
 . 8      .send (handle -> {
 . 9          // result of the processing in response to the 
10          IF (handle.succeeded ()) {
 . 11              // here get The result is an HTML text, direct print 
12             System.out.println(handle.result().bodyAsString());
13         }
14     });
15 }

The above code is what I want to request Sina's home page, you can see, just before calling the send method, calling ssl method, and designated as true can be.

 

Guess you like

Origin www.cnblogs.com/endv/p/11257566.html