springboot发送http请求
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot发送http请求相关的知识,希望对你有一定的参考价值。
springboot中实现http请求调用api
创建发送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(); } }
添加本地测试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); } }
访问localhost:8080/hello查看调用结果
curl http://localhost:8080/hello
以上是关于springboot发送http请求的主要内容,如果未能解决你的问题,请参考以下文章
springboot中使用restTemplate发送带参数和请求头的post,get请求
4种Springboot RestTemplate 服务里发送HTTP请求用法
无法反序列化从 Springboot POST 映射函数上的 Angular http post 请求发送的 POJO
springboot怎么将oauth2的参数通过http发送