RestTemplate 服务间接口调用

目前使用的是exchange 这个方法,主要参数有

  • String url:被调用方的url
  • HttpMethod method:post还是get还是其他的
  • HttpEntity<com.lyq.User> httpEntity:包含入参对象,请求头HttpHeaders
  • 返回类型:可以为String或其他,也可以为ParameterizedTypeReference<User>()

 

如果被调用方的入参对象没有加@RequestBody,那么只能是MultiValueMap,否则调用有问题。

 

调用方(localhost:8070)

package com.lyq.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyq.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    RestTemplate restTemplate;
    @GetMapping("/a")
    public User getUser(){

        HttpHeaders headers = new HttpHeaders();
        User user = new User();
        user.setAge(22);
        user.setId("001");
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
        MultiValueMap map = new LinkedMultiValueMap();
        map.add("age",22);
        map.add("id","001");
//        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<MultiValueMap>(map,headers);
//        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject,headers);
        HttpEntity<com.lyq.User> httpEntity = new HttpEntity<>(user,headers);

        ResponseEntity<User> responseEntity = restTemplate.exchange("http://localhost:8080/all/a", HttpMethod.POST, httpEntity, new ParameterizedTypeReference<User>() {});

     
     User body = responseEntity.getBody(); 
     System.out.println(responseEntity.getBody());
return body;
    }
}

RestTemplate的config

package com.lyq.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ReatTemplateConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

被调用方(localhost:8080)

package com.example.producter.controller;

import com.example.producter.dto.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/all")
public class TestController {

    @PostMapping("/a")
    public User getString(@RequestBody User user ){
        System.out.println(user);

        return user;
    }

}

 

posted @ 2021-08-23 00:03  JacksonLiyq  阅读(269)  评论(0编辑  收藏  举报