当前位置:网站首页>Resttemplate usage details and pit stepping records

Resttemplate usage details and pit stepping records

2022-06-09 11:57:00 sunnyday0426

1.1 sketch

Need to use... In recent projects http Third party services are called in the form of , What we use in our project is RestTemplate Make interactive calls . Unlike what we used to write HttpClient, Need to write a lot of tool classes ,RestTemplate It's basically out of the box , This article mainly introduces its application in spring boot Basic projects in use , For daily development, etc , Basically, there is no problem .

1.1.1 Rest

When talking about REST when , A common mistake is to think of it as “ be based on URL Of Web service ”—— take REST As another type of remote procedure call (remote procedure call,RPC) Mechanism , It's like SOAP equally , It's just a simple HTTP URL To trigger , Instead of using SOAP a large number of XML Namespace

On the contrary ,REST And RPC Almost nothing .RPC It's service-oriented , And focus on actions and actions ; and REST It's resource oriented , Emphasize things and terms that describe an application .

More succinctly ,REST Is to transfer the state of resources from the server to the client in the form most suitable for the client or server ( Or vice versa ).

stay REST in , Resources through URL Identify and locate . as for RESTful URL There are no strict rules in the structure of , however URL Should be able to identify resources , Instead of simply sending a command to the server . Again , The core of attention is things , Not behavior .

1.1.2 Spring How to use Rest resources

With the help of RestTemplate,Spring Applications are easy to use REST resources
Spring Of RestTemplate Access design patterns that use the template method

The template method delegates the part of the process related to a specific implementation to the interface , And different implementations of this interface define different behaviors of the interface

RestTemplate Defined 36 One and REST How resources interact , Most of them correspond to HTTP Methods .
Actually , There's only 11 An independent method , Ten of them have three overload forms , The eleventh is overloaded six times , In this way, a total of 36 A way .

  • delete()
    In particular URL Execute... On resources HTTP DELETE operation

  • exchange()
    stay URL To execute specific HTTP Method , Returns the... Containing the object ResponseEntity, This object is mapped from the response body

  • execute()
    stay URL To execute specific HTTP Method , Returns an object from the response body map

  • getForEntity()
    Send a HTTP GET request , Back to ResponseEntity Contains the objects mapped by the response body

  • getForObject()
    Send a HTTP GET request , The returned request body will be mapped to an object

  • postForEntity()
    POST Data to a URL, Returns... That contains an object ResponseEntity, This object is mapped from the response body

  • postForObject()
    POST Data to a URL, Returns the object formed by matching the response body

  • headForHeaders()
    send out HTTP HEAD request , Return contains specific resources URL Of HTTP head

  • optionsForAllow()
    send out HTTP OPTIONS request , Return to specific URL Of Allow Header information

  • postForLocation()
    POST Data to a URL, Returns the... Of the newly created resource URL

  • put()
    PUT Resources to specific URL

actually , because Post The non idempotent nature of the operation , It can almost replace other CRUD operation

1.2 Get request

RestTemplate Of get There are several methods above , It can be divided into two categories : getForEntity() and getForObject()

First of all to see getForEntity() Return value type of ResponseEntity

<T> ResponseEntity<T> getForEntity()

to glance at ResponseEntity The document description of :

You can see It inherited HttpEntity, Encapsulates the returned response information , Include Response state , Response head and Response body

Before testing, we first Create a Rest service , The simulation provides Rest data , Here is given Controller Layer code :

@RestController
public class UserController {
    

    @Autowired
    private UserService userService;

    @RequestMapping(value = "getAll")
    public List<UserEntity> getUser() {
    
        List<UserEntity> list = userService.getAll();
        return list;
    }

    @RequestMapping("get/{id}")
    public UserEntity getById(@PathVariable(name = "id") String id) {
    
        return userService.getById(id);
    }
    
    @RequestMapping(value = "save")
    public String save(UserEntity userEntity) {
    
        return " Saved successfully ";
    }

    @RequestMapping(value = "saveByType/{type}")
    public String saveByType(UserEntity userEntity,@PathVariable("type")String type) {
    
        return " Saved successfully ,type="+type;
    }
}

1.2.1 test : getForEntity

No parameters getForEntity Method

 @RequestMapping("getForEntity")
    public List<UserEntity> getAll2() {
    
        ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost/getAll", List.class);
        HttpHeaders headers = responseEntity.getHeaders();
        HttpStatus statusCode = responseEntity.getStatusCode();
        int code = statusCode.value();

        List<UserEntity> list = responseEntity.getBody();

        System.out.println(list.toString());
        return list;

    }

Parametric getForEntity request , parameter list , have access to {} Conduct url Path placeholder

 // Parametric  getForEntity  request , parameter list 
    @RequestMapping("getForEntity/{id}")
    public UserEntity getById2(@PathVariable(name = "id") String id) {
    

        ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost/get/{id}", UserEntity.class, id);
        UserEntity userEntity = responseEntity.getBody();
        return userEntity;
    }

Parametric get request , Use map Package parameters

    // Parametric  get  request , Use map Package parameters 
    @RequestMapping("getForEntity/{id}")
    public UserEntity getById4(@PathVariable(name = "id") String id) {
    
        HashMap<String, String> map = new HashMap<>();
        map.put("id",id);

        ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost/get/{id}", UserEntity.class, map);
        UserEntity userEntity = responseEntity.getBody();

        return userEntity;
    }

So we can get Http All requested information .

however , Usually we don't want to Http All requested information , Just need the corresponding body , In this case ,RestTemplate Provides getForObject() Method is used to get only Response body information
getForObject and getForEntity The usage is almost the same , Indicates that the return value returns Response body , Save us Go again getBody()

1.2.2 test : getForObject

No parameters getForObject request

    // No parameters  getForObject  request 
    @RequestMapping("getAll2")
    public List<UserEntity> getAll() {
    
        List<UserEntity> list = restTemplate.getForObject("http://localhost/getAll", List.class);
        System.out.println(list.toString());
        return list;
    }

Parametric getForObject request , Use the parameter list

    // Parametric  getForObject  request 
    @RequestMapping("get2/{id}")
    public UserEntity getById(@PathVariable(name = "id") String id) {
    
        UserEntity userEntity = restTemplate.getForObject("http://localhost/get/{id}", UserEntity.class, id);
        return userEntity;
    }

Parametric get request , Use map Encapsulate request parameters

    // Parametric  get  request , Use map Encapsulate request parameters 
    @RequestMapping("get3/{id}")
    public UserEntity getById3(@PathVariable(name = "id") String id) {
    
        HashMap<String, String> map = new HashMap<>();
        map.put("id",id);
        UserEntity userEntity = restTemplate.getForObject("http://localhost/get/{id}", UserEntity.class, map);
        return userEntity;
    }

1.3 Post request

I understand get After the request ,Post The request becomes very simple , We can see post There are the following methods :

1.3.1 test :postForEntity

post request , preservation UserEntity Antithetic image

    //post  request , Submit  UserEntity  Antithetic image 

    @RequestMapping("saveUser")
    public String save(UserEntity userEntity) {
    
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/save", userEntity, String.class);
        String body = responseEntity.getBody();
        return body;
    }

Browser access : http://localhost/saveUser?username=itguang&password=123456&age=20&[email protected]
Let's debug again , see responseEntity Information in

Parametric postForEntity request

   //  Parametric  postForEntity  request 
    @RequestMapping("saveUserByType/{type}")
    public String save2(UserEntity userEntity,@PathVariable("type")String type) {
    
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class, type);
        String body = responseEntity.getBody();
        return body;
    }

    //  Parametric  postForEntity  request , Use map encapsulation 
    @RequestMapping("saveUserByType2/{type}")
    public String save3(UserEntity userEntity,@PathVariable("type")String type) {
    
        HashMap<String, String> map = new HashMap<>();
         map.put("type", type);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class,map);
        String body = responseEntity.getBody();
        return body;
    }

Our browser access : localhost/saveUserByType/120?username=itguang&password=123456&age=20&[email protected]

It will return : Saved successfully ,type=120

With other request methods , Due to infrequent use , So I won't talk about

1.4 Record on pit :restTemplate Of exchange Method get Ask for the newspaper 400 Bad request【restTemplate Bug】 Solutions for

1.4.1 Filling record

The following code ,url=http://www.baidu.com Time request message 400

HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Authorization", authorization);
        requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        if (map != null) {
    
            map.forEach((k, v) -> {
    
                if (StringUtils.isNotBlank(v)) {
    
                    requestBody.add(k,v);
                }
            });
        }
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
        try {
    
            ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            return new HttpResDTO(res.getStatusCodeValue(), res.getBody());
        } catch (HttpClientErrorException ex) {
    
            log.error("rest template for face exception, error code: {}, error message: {}", ex.getRawStatusCode(), ex.getMessage());
            return new HttpResDTO(ex.getRawStatusCode(), ex.getResponseBodyAsString());
        } catch (UnknownHttpStatusCodeException e) {
    
            String responseBodyAsString = e.getResponseBodyAsString();
            log.warn("UnknownHttpStatusCodeException:{}",responseBodyAsString);
            JSONObject parse = JSONObject.parseObject(responseBodyAsString);
            throw new RuntimeException(parse.get("message").toString());
        }

1.4.2 Solution

get Request directly in url Upper spelling parameters , Such as ?type=1&name=xx
String uri =tempUrl + “?keys={keys}”; adopt map Pass on keys

Map<String, String> map = new HashMap<>(1);
map.put(“keys”, “xdfdf”);
ResponseEntity res = restTemplate.getForEntity(url, String.class, map);
原网站

版权声明
本文为[sunnyday0426]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091059559719.html