Sample code for using HTTP requests in spring boot

Because of the project requirements, the two systems need to communicate. After some research, it is decided to use HTTP request.

The server has nothing to say. It is originally accessed using a web page. Therefore, after the spring boot is started, the interface of the controller layer is automatically exposed. The client can call the corresponding URL, so it is mainly the client.

First, I customized a tool class devicefactoryhttp for handling HTTP requests. Since it is URL access, there are two problems to deal with, one is the URL of the request service, and the other is the parameters of the request server, The message header of the client requests the URL of the service: the URL of the request server. I define the same URL as the client. The parameters of the server: there are two parameters of the server. One is encapsulated, similar to the following:

http://localhost:8080/switch/getAllStatus?data {"interface name”:”getAllStudentStaus”}

One is not encapsulated, like the following:

http://localhost:8080/switch/getStudentInfoByName?name=zhangSan

The first is encapsulated:

1: Initialize httpclient

2: Get the requested URL. Because the URL defined by my server is the same as that of the client, I directly use the URL of the requesting client

Get the URL and split it according to / because this is the test environment, the production environment IP, and the port number (domain name) is definitely not localhost. Some will be preceded by the project name, so I will replace it with the corresponding value of split.

3: Assemble request parameters and call HTTP request

Get the requested parameters first, and then assemble the parameters after the URL, urlencoder Don't forget about encode, because the parameters will have some symbols. You need to encode the parameters and then add the URL, otherwise an exception will be thrown. Set headers: because some information will be taken out from the request header by the server, I will also set the request header of the client to the request of the server. Just spell the requested URL and the requested parameters Execute (get) executed the request.

The above is that my browser directly sends the request as a parameter to my client, so I can directly obtain the URL from the request. Some do not have a request, so I need to get it from the request context.

Not encapsulated:

First, get the name of the request from the context

2: After you have the request, you have the URL. Next, you can parse the request parameters. Because this parameter is not encapsulated, you can get all the request parameters

3: Send HTTP request

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>