springboot中实现http请求调用api

创建发送http请求service层

importorg.springframework.http.*;importorg.springframework.stereotype.Service;importorg.springframework.util.MultiValueMap;importorg.springframework.web.client.RestTemplate;/***@Author冯战魁*@Date2018/1/23下午5:43*/@ServicepublicclassHttpClient{publicStringclient(Stringurl,HttpMethodmethod,MultiValueMap<String,String>params){RestTemplateclient=newRestTemplate();HttpHeadersheaders=newHttpHeaders();//请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);HttpEntity<MultiValueMap<String,String>>requestEntity=newHttpEntity<MultiValueMap<String,String>>(params,headers);//执行HTTP请求ResponseEntity<String>response=client.exchange(url,HttpMethod.POST,requestEntity,String.class);returnresponse.getBody();}}

添加本地测试url localhost:8080/hello

importcom.example.demo.service.HttpClient;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.http.*;importorg.springframework.util.LinkedMultiValueMap;importorg.springframework.util.MultiValueMap;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/***@Author冯战魁*@Date2018/1/8上午11:17*/@RestControllerpublicclassHelloController{@AutowiredHttpClienthttpClient;@RequestMapping("/hello")publicStringhello(){//apiurl地址Stringurl="http://xxxx";//post请求HttpMethodmethod=HttpMethod.POST;//封装参数,千万不要替换为Map与HashMap,否则参数无法传递MultiValueMap<String,String>params=newLinkedMultiValueMap<String,String>();params.add("access_token","xxxxx");//发送http请求并返回结果returnhttpClient.client(url,method,params);}}

访问localhost:8080/hello查看调用结果

curl http://localhost:8080/hello