springboot发送请求,使用RestTemplate 方式

springboot中实现http请求调用api

  1. 创建发送http请求service层

    import org.springframework.http.*;
    import org.springframework.stereotype.Service;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    /**
     * @Author 冯战魁
     * @Date 2018/1/23 下午5:43
     */
    @Service
    public class HttpClient {
        public String client(String url, HttpMethod method, MultiValueMap<String, String> params){
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //  请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            //  执行HTTP请求
            ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
            return response.getBody();
        }
    }
  2. 添加本地测试url localhost:8080/hello

    import com.example.demo.service.HttpClient;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.*;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    
    /**
     * @Author 冯战魁
     * @Date 2018/1/8 上午11:17
     */
    @RestController
    public class HelloController {
        @Autowired
        HttpClient httpClient;
        @RequestMapping("/hello")
        public String hello(){
            //api url地址
            String url = "http://xxxx";
            //post请求
            HttpMethod method =HttpMethod.POST;
            // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
            params.add("access_token", "xxxxx");
            //发送http请求并返回结果
            return httpClient.client(url,method,params);
        }
    }
  3. 访问localhost:8080/hello查看调用结果

    curl http://localhost:8080/hello

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仰望星空007

你的鼓励就是我最大的动力!谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值