Spring Boot RestTemplate

getForObject

getForObject指get请求,并返回一个Object对象。这里有2个方法参数

  • 第1个参数:请求的url地址
  • 第2个参数:返回的结果类型,这里String.class表示返回结果是一个字符串。
@RestController  
public class ClientController {  
    @Autowired  
    RestTemplate restTemplate;  

    @RequestMapping("/client")  
    public String client() {  
        //通过restTemplate请求rest服务端  
        String result = restTemplate.getForObject("http://localhost:8081/server", String.class);  
        return result;  
    }  

getForEntity

  • getForEntity和getForObject的用法是一样的,只是其返回结果是一个ResponseEntity,其中包含了更多的响应信息
ResponseEntity response = restTemplate.getForEntity("http://localhost:8081/server",String.class);  
response.getHeaders();      //响应头  
response.getStatusCode();   //响应码  
response.getBody();         //响应体,即前面的result  

postForObject

String response = restTemplate.postForObject("http://localhost:8081/server?param1={1}&param2={2}", null, String.class, "hello", "world");  

HttpEntity

//请求体  
Map map = new HashMap();  
map.put("param1", "hello");  
map.put("param2", "world");  
//请求头  
MultiValueMap headers = new HttpHeaders();  
headers.add("Accept", "text/xml");  
//请求内容封装成httpEntity  
HttpEntity httpEntity= new HttpEntity(map,headers);  

restTemplate.postForObject("http://localhost:8081/server", httpEntity, String.class);  

postForEntity

和getForEntity原理是一样的

配置超时

@Bean  
public RestTemplate restTemplate(){  
    RestTemplate restTemplate = restTemplateBuilder  
        .setConnectTimeout(1000)        //连接超时为1秒  
        .setReadTimeout(1000)           //请求超时为1秒  
        .build();  
    return restTemplate;  
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值