相关文章推荐
腹黑的鸵鸟  ·  Python操作Redis大全 - 知乎·  1 年前    · 
苦恼的打火机  ·  CSS – Sass & SCSS - ...·  1 年前    · 
打篮球的红酒  ·  could not find ...·  2 年前    · 
豪爽的烤面包  ·  javascript - Using ...·  2 年前    · 

RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能,但只有理解了HttpEntity的组成结构(header与body),且理解了与uriVariables之间的差异,才能真正掌握其用法。

此文章主要写了 Get 和 Post请求的 ForObject ,ForEntity 和exchange这三种方式的提交数据

在这里插入图片描述
话不多说 直接上代码 在启动文件中 配置resttemplate的Bean
如果是get请求中携带body中的json数据 这样注入是会报错的 ,代码下方有解决方案

@Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
@org.springframework.web.bind.annotation.RestController
@RequestMapping()
public class RestController {
    @Autowired
    private RestTemplate restTemplate;
     * 使用getForObject  url直接携带参数访问  返回的结果是String
     * @return
    @GetMapping("/get1")
    public String getTest1(@RequestParam String id){
        String resop = restTemplate.getForObject("http://localhost:6666/gettest/?id=1", String.class);
        return resop+"远程调用get1";
     * 使用getForObject  url的参数使用map方式   需要使用这种格式id={id}  返回的结果是String
     * @param id
     * @return
    @GetMapping("/get2")
    public String getTest2(@RequestParam String id){
        Map<String,String> map = new HashMap();
        map.put("id","1");
        String resop = restTemplate.getForObject("http://localhost:6666/gettest/?id={id}", String.class,map);
        return resop+"远程调用get2";
     * 使用getForEntity   url直接携带参数访问  返回的结果是ResponseEntity类型
     * response.getBody()得到 get返回的data
     * @param id
     * @return
    @GetMapping("/get3")
    public String getTest3(@RequestParam String id){
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:6666/gettest/?id=1",String.class);
        String body = response.getBody();
        return body+"远程调用get3";
     * 使用getForEntity   url直接参数使用map  返回的结果是ResponseEntity类型
     * response.getBody()得到 get返回的data
     * @param id
     * @return
    @GetMapping("/get4")
    public String getTest4(@RequestParam String id){
        Map<String,String> map = new HashMap();
        map.put("id","1");
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:6666/gettest/?id={id}",String.class,map);
        String body = response.getBody();
        return body+"远程调用get4";
     * 使用exchange   请求头部body携带json数据
     *  * 当使用get请求需要携带 body中的参数的时候  需要重写Http  版本号必须是4.3以上
     *    定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类,以支持GET请求携带body数据
     * @param id
     * @return
    @GetMapping("/get5")
    public String getTest5(@RequestParam String id){
         * 1)url: 请求地址;
         *      2)method: 请求类型(如:POST,PUT,DELETE,GET);
         *      3)requestEntity: 请求实体,封装请求头,请求内容
         *      4)responseType: 响应类型,根据服务接口的返回类型决定
         *      5)uriVariables: url中参数变量值
        String jsonData = "{\"test\":\"1234\",\"score\":\"1\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonData, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:6666/getbody/?id=1", HttpMethod.GET, httpEntity, String.class);
        return responseEntity.getBody()+"远程调用get5"+responseEntity.getStatusCode();
     * url参数 使用map  方式
     * @param id
     * @return
    @GetMapping("/get6")
    public String getTest6(@RequestParam String id){
        //封装url参数
        Map<String,String> map = new HashMap();
        map.put("id","1");
        //设置头部body携带json数据
        String jsonData = "{\"test\":\"6666\",\"score\":\"88888\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonData, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:6666/getbody/?id={id}", HttpMethod.GET, httpEntity, String.class,map);
        return responseEntity.getBody()+"远程调用get6"+responseEntity.getStatusCode();
     * 使用本接口访问 直接携带json数据 封装成远程调用的参数 去访问
     * 当使用get请求需要携带 body中的参数的时候  需要重写Http  版本号必须是4.3以上
     * 定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类,以支持GET请求携带body数据
    @GetMapping("/getbody")
    public String getBody(@RequestParam String id, @RequestBody JSONObject json){
        //封装url参数
        Map<String,String> map = new HashMap();
        map.put("id",id);
        //设置头部body携带json数据
        String jsonData = json.toJSONString




    
();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonData, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:6666/getbody/?id={id}", HttpMethod.GET, httpEntity, String.class,map);
        return responseEntity.getBody()+"远程调用get7"+responseEntity.getStatusCode();
     * postForObject  直接带参数
     * @param id
     * @return
    @PostMapping("/post1")
    public String postTest1(@RequestParam String id){
        String s = restTemplate.postForObject("http://localhost:6666/posttest/?id=1", null, String.class);
        return id+"测试post"+s;
     * postForObject 使用map  封装 参数
     * @param id
     * @return
    @PostMapping("/post2")
    public String postTest2(@RequestParam String id){
        //封装url参数
        Map<String,String> map = new HashMap();
        map.put("id",id);
        String s = restTemplate.postForObject("http://localhost:6666/posttest/?id={id}", null, String.class, map);
        return id+"测试post"+s;
     * postForObject  头部携带Json 数据
     * @param id
     * @param json
     * @return
    @PostMapping("/postbody")
    public String postBody(@RequestParam String id, @RequestBody JSONObject json){
        //封装url参数
        Map<String,String> map = new HashMap();
        map.put("id",id);
        //设置头部body携带json数据
        String jsonData = json.toJSONString();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonData, headers);
        String s = restTemplate.postForObject("http://localhost:6666/postbody/?id={id}", httpEntity, String.class, map);
        return id+"测试post接收json数据"+s;
     * post  使用通用的 exchange 访问
     * 返回的结果是ResponseEntity  从中拿数据getBody
    @PostMapping("/postbody2")
    public String postBody2(@RequestParam String id, @RequestBody JSONObject json){
        //封装url参数
        Map<String,String> map = new HashMap();
        map.put("id",id);
        //设置头部body携带json数据
        String jsonData = json.toJSONString();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonData, headers);
        ResponseEntity<String> exchange = restTemplate.exchange("http://localhost:6666/postbody/?id={id}", HttpMethod.POST, httpEntity, String.class, map);
        return "测试post接收json数据"+exchange.getBody()+":"+exchange.getStatusCode();

当使用get请求需要携带 body中的参数的时候 需要重写Http 版本号必须是4.3以上
定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类,以支持GET请求携带body数据

pom文件引入

		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.4</version>
        </dependency>

resttemplate使用配置文件方式 需要把springboot中的@Bean resttemplate注释掉

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
        restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory());
        return restTemplate;
    // 设置超时时间
    private SimpleClientHttpRequestFactory getClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        // Connect timeout 3s
        clientHttpRequestFactory.setConnectTimeout(60000);
        // Read timeout 3s
        clientHttpRequestFactory.setReadTimeout(60000);
        return clientHttpRequestFactory;

定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类
在上面的resttemplate配置文件中需要注入

public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
    @Override
    protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
        if (httpMethod == HttpMethod.GET) {
            return new HttpGetRequestWithEntity(uri);
        return super.createHttpUriRequest(httpMethod, uri);
     * 定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类,以支持GET请求携带body数据
    private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
        public HttpGetRequestWithEntity(final URI uri) {
            super.setURI(uri);
        @Override
        public String getMethod() {
            return HttpMethod.GET.name();

测试的远程端代码如下 端口号 是6666

@RestController
@RequestMapping()
public class HttpController {
    @GetMapping("/gettest")
    public String getTest(@RequestParam String id){
        System.out.println("测试成功");
        return id+"测试get";
    @GetMapping("/getbody")
    public String getBody(@RequestParam String id, @RequestBody JSONObject json){
        System.out.println("输出"+json.toJSONString());
        return id+"测试get接收json数据"+json.toString();
    @PostMapping("/posttest")
    public String postTest(@RequestParam String id){
        System.out.println("post测试id"+id);
        return id+"测试post";
    @PostMapping("/postbody")
    public String postBody(@RequestParam String id, @RequestBody JSONObject json){
        System.out.println("post测试json"+id+"  json:"+json.toString());
        return id+"测试post接收json数据"+json.toString();
                    RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能,但只有理解了HttpEntity的组成结构(header与body),且理解了与uriVariables之间的差异,才能真正掌握其用法。此文章主要写了 Get 和 Post请求的 ForObject ,ForEntity  和exchange这三种方式的提交数据话不多说  直接上代码 在启动文件中 配置resttemplate的Bean如果是get请求中携带body中的json数据 这样注入是会报错的  ,
				
这里写目录标题一、介绍GET 请求getForObjectgetForEntityPOST 请求postForEntitykey/value格式JSON格式postForObjectpostForLocationPUT 请求DELETE 请求exchange 通用方法 RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 excha
前言一、RestTemplateSpring Boot RestTemplate使用get请求请求头header的设置及传参方式1. 有参数,没有请求头 2. 有请求头,没参数 3. 有请求头,有参数代码如下:
String url = "http://localhost:8081/aa"; //headers HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("api-version", "1.0"); //b...
Spring 的 RestTemplate 是一个健壮的、流行的基于 JavaHttp客户端。但是在RestTemplateGet请求不能直接传一个javabean作为参数,所以可以对RestTemplate的UriTemplateHandler接口进行拓展,支持直接传javabean ......
目前遇到一个对接需求,对方公司提供了一个接口,请求方法为GET,传参是在body中的json格式数据。 针对这个需求,在postman中进行测试,请求成功,后续需要用java进行接口调用。 首先,我们要了解 RestTemplate 请求方法和 HTTP 请求方法的对应关系。 get 请求 String urlStr = "url"; UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlStr) .queryParam("参数1", "....") .queryParam("参数2", "...."); HttpHeaders headers = new
RestTemplate请求方法参数介绍 第一个:getForEntity(String url, Class responseType, uriVariables) getForEntity(URI url, Class responseType) getForEntity(String url, Class responseType, Object… uriVariables) url:请求地址,如果是URI,则可以通过UriComponents.toUri()构建一个uri, UriComponen
文章目录一、RestTemplate 简介1、RestTemplate 概述2、RestTemplate 的配置项3、RestTemplate 请求方式二、RestTemplate 使用1、Get请求方式2、Post 请求方式3、Put 请求方式3、Delete 请求4、RestTemplate 其他方法 一、RestTemplate 简介 1、RestTemplate 概述 2、RestTemp...
String qd="[{key:\"ZB\",value:\"1\",bijiaofu:1}]"; //qd= URLEncoder.encode(qd,"utf-8"); RestTemplate restTemplate = new RestTemplate(); String url="http://10.0.10.129:10091/api/ccform/zzCcformDataview/getTableDataById?" + "dvid=1408263043573420034" + "&am.
RestTemplate是Spring框架中的一个HTTP客户端工具,可以用来发送HTTP请求。在发送GET请求时,可以通过URL传递参数,也可以通过URI传递参数。具体的实现方式如下: 1. 通过URL传递参数 ```java RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:808/user?id={id}&name={name}"; Map<String, String> params = new HashMap<>(); params.put("id", "1"); params.put("name", "张三"); String result = restTemplate.getForObject(url, String.class, params); 2. 通过URI传递参数 ```java RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:808/user/{id}/{name}"; Map<String, String> params = new HashMap<>(); params.put("id", "1"); params.put("name", "张三"); URI uri = UriComponentsBuilder.fromUriString(url).build(params); String result = restTemplate.getForObject(uri, String.class); 以上两种方式都可以实现GET请求参数的传递。其中,第一种方式通过URL传递参数,需要在URL中使用占位符{}来表示参数,然后在调用RestTemplate的getForObject方法时,将参数值传递进去。第二种方式通过URI传递参数,需要使用UriComponentsBuilder来构建URI,然后将参数值传递进去。