1. The background

Generally, HTTP requests are sent using Apache’s HttpClient, which is more flexible. Rest-style services often provided in spring Cloud. RestTemplate provides a simple and convenient way to use a template class to perform HTTP operations.

Or, can consider to use org. According to the needs of your springframework. Web. Reactive. Client. The WebClient have synchronous, more modern API and support asynchronous transmission scheme and flow.

2. Knowledge

HttpClient is a templated HTTP request framework suitable for invoking REST requests. It is widely used in SpringCloud microservice framework.

Example 3.

(1) Send get request

Use getForEntity: Initiate get requests. Request mode without parameters.

Super simple, see below:

String url = "http://your_url";
ResponseEntity<String> result = restTemplate.getForEntity(url,String.class);
Copy the code

Use getForEntity: Initiate get requests. Concatenate your own parameter string.

This approach uses map to pass parameters. If you have Chinese characters, you need to do urlencode.

The String url = "http://127.0.0.1:8080/login? name={name}"; Map<String,String> map = new HashMap<>(); map.put("name","join"); ResponseEntity<String> result = restTemplate.getForEntity(url,String.class,map);Copy the code

Use getForEntity: Initiate get requests. First concatenate URI object parameters.

Build an object with UriComponents and expand to replace the actual values of the parameters so it looks clearer.

  • Expand (): replace parameters.
  • Encode (): encode, using UTF-8 by default.
UriComponents uriComponents = UriComponentsBuilder
.fromUriString("http://example.com/hotels/{hotel}/bookings/{booking}").build();
URI uri = uriComponents.expand("42", "21").encode().toUri();
ResponseEntity<String> result = restTemplate.getForEntity(uri,String.class);
Copy the code

Use getForEntity: Convert the returned response content into an entity object

The following argument is passed to a class, in this case just pass user.class.

The String url = "http://127.0.0.1:8080/login? name={name}"; Map<String,String> map = new HashMap<>(); map.put("name","zhang3"); ResponseEntity<User> result = restTemplate.getForEntity(url,User.class,map);Copy the code

Send a GET request with a request header

Build an HttpEntity, pass in the Header object, and then send it.

The String url = "http://127.0.0.1:8080/xxx; HttpHeaders resultRequestHeader = new HttpHeaders(); resultRequestHeader.add("charset", "UTF-8"); resultRequestHeader.setContentType(MediaType.APPLICATION_JSON); LinkedMultiValueMap<String, Object> resultParamMap = new LinkedMultiValueMap<>(); HttpEntity<String> resultHttpEntity = new HttpEntity<>(null, resultRequestHeader); ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET,resultHttpEntity,String.class);Copy the code

(2) Send PSOT request

Post requests are sent using postForEntity.

Just like get, postForEntity.

The String url = "http://127.0.0.1:8080/login"; LinkedMultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); paramMap.add("username", "zhangsan"); paramMap.add("password", "123456"); paramMap.add("randomStr",String.valueOf(System.currentTimeMillis())); HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, requestHeaders); ResponseEntity<String> exchange = restTemplate.postForEntity(url, httpEntity, String.class); String resultRemote = exchange.getBody(); // Get the returned valueCopy the code

(3) Use the Exchange method

Exchange method: First construct ResponseEntity and then send the request

Performs the request specified in the given, RequestEntity and returns the ResponseEntity form. A RequestEntity is usually built in a Builder chain, such as method signature:

public <T> ResponseEntity<T> exchange(RequestEntity<? > entity, Class<T> responseType) throws RestClientExceptionCopy the code

The sample

MyRequest body = ...
 RequestEntity request = RequestEntity
     .post(new URI("https://example.com/foo"))
     .accept(MediaType.APPLICATION_JSON)
     .body(body);
 ResponseEntity<MyResponse> response = template.exchange(request, MyResponse.class);
Copy the code

Exchange method: Build a RequestEntity and send a parameter request with a generic type

The method signature

public <T> ResponseEntity<T> exchange(RequestEntity<? > entity, ParameterizedTypeReference<T> responseType) throws RestClientExceptionCopy the code

See the following example:

MyRequest body = ...
 RequestEntity request = RequestEntity
     .post(new URI("https://example.com/foo"))
     .accept(MediaType.APPLICATION_JSON)
     .body(body);
 ParameterizedTypeReference<List<MyResponse>> myBean =
     new ParameterizedTypeReference<List<MyResponse>>() {};
 ResponseEntity<List<MyResponse>> response = template.exchange(request, myBean);
Copy the code

Exchange approach: Works with generic collections

Executes the HTTP method on the given URI template, writes the given request entity to the request, and returns the ResponseEntity form. Given ParameterizedTypeReference used to pass the generic type of entity information:

ParameterizedTypeReference generally used to pass generic collections Such as the List < MyBean >.

public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<? > requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientExceptionCopy the code

Example:

ParameterizedTypeReference<List<MyBean>> myBean =
     new ParameterizedTypeReference<List<MyBean>>() {};

 ResponseEntity<List<MyBean>> response =
     template.exchange("https://example.com",HttpMethod.GET, null, myBean);
Copy the code

(4) Use the execute method

Execute method request

Make HTTP method requests to URI templates and use RequestCallback for processing and preparation of the request. And use ResponseExtractor to process “response results”.

Signature:

@Nullable
public <T> T execute(String url,
                               HttpMethod method,
                               @Nullable
                               RequestCallback requestCallback,
                               @Nullable
                               ResponseExtractor<T> responseExtractor,
                               Object... uriVariables)
                        throws RestClientException
Copy the code

4. Reference:

Docs. Spring. IO/spring – fram…