标题RestTemplate
使用步骤
提供一个Config类
这个模板类并不能像redis或mongoDb的模板那样通过propertes轻松使用,需要配置一个config对象
提供了快捷的http请求与响应
使用场景:多个服务器之间的访问 需要获取参数时,不通过前端去请求,直接通过服务器发起
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@Configuration
public class RestTemplateConfig {
/**
* 消息转换器
* @param factory
* @return
*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
RestTemplate restTemplate = new RestTemplate(factory);
// 支持中文编码
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
/**
*
* 连接响应时间
* 指定了链接相关配置,链接超时时间
*
* @return
*/
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//单位为ms
factory.setReadTimeout(5000);
factory.setConnectTimeout(5000);
return factory;
}
}
配置后的使用
@Autowired private RestTemplate restTemplate;
String data = this.restTemplate.getForObject(url, String.class);
//返回一个ResponseEntity对象 参数2是期望返回的结果类型
ResponseEntity<String> aa = this.restTemplate.getForEntity(url, String.class, "aa");
/*
这个工具类也提供了各种请求方式 post get delete put 等,都是有的
*/