通过Resttemplate调用第三方接口

GET请求

    import org.springframework.web.client.RestTemplate;

    @Resource
    RestTemplate restTemplate;

    @Bean
    @LoadBalanced
    public  RestTemplate getRestTemplate(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(10000);
        httpRequestFactory.setConnectTimeout(10000);
        httpRequestFactory.setReadTimeout(10000);
        return new RestTemplate(httpRequestFactory);
    }

    @Override
    public List<SysStudent> getListInfo() throws Exception {
        Map<String, Object> json=new HashMap<>();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        Map<String,Object> params = new HashMap<>();
        params.put("phoneNumber",phoneNumber);
        restTemplate.getForObject("http://192.168.2.136:8080/api/list?phoneNumber={phoneNumber}",String.class,params);
        return null;
    }

POST请求

public String post(Student student) {
      Map<String, Object> json = new HashMap<>();
      HttpHeaders requestHeaders = new HttpHeaders();
      requestHeaders.setContentType(MediaType.APPLICATION_JSON);
      HttpEntity entity = new HttpEntity(student, requestHeaders);
      restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
      String result = null;
      try{
           result =  restTemplate.postForObject("http://192.168.2.136:8080/api/complete",entity, String.class));
      }catch (Exception e){
           log.info("请求失败",e);
      }
      return result;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值