0%

springboot使用RestTemplate

开发带参数的restful接口

@RequestParam

// URL路径格式: /trigger?taskId=xxxxxxxxxx
@GetMapping("/trigger")
public String trigger(@RequestParam(value = "taskId") String taskId) {
    tableCompareService.compare(taskId);
    return "ok";
}

@PathVariable

// URL路径格式: /trigger/taskxxxxxxxxxx
@GetMapping("/trigger/{taskId}")
public void demo(@PathVariable(name = "taskId") String taskId) {
    System.out.println("taskId=" + taskId);
}

@RequestBody

// 请求内容转化成对象
@PostMapping(path = "/demo")
public void demo1(@RequestBody Person person) {
    System.out.println(person.toString());
}

RestTemplateConfig.java类

@Configuration
public class RestTemplateConfig {
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    // 超时时间自定义
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

使用RestTemplate调用其它接口样例

@Service
public class demoService {
 
    @Autowired
    private RestTemplate restTemplate;
 
    public String get(Integer id){
        return restTemplate.getForObject("http://localhost:8080/user?userId=id",String.class);
    }
}
@GetMapping("getForEntity/{id}")
public User getById(@PathVariable(name = "id") String id) {
    ResponseEntity<User> response = restTemplate.getForEntity("http://localhost/get/{id}", User.class, id);
    User user = response.getBody();
    return user;
}
@RequestMapping("saveUser")
public String save(User user) {
    ResponseEntity<String> response = restTemplate.postForEntity("http://localhost/save", user, String.class);
    String body = response.getBody();
    return body;
}

针对delete put等一些方法没有返回值或者其它问题,可以使用restTemplate.exchange()方法解决.