SpringBoot RestTemplate GET POST请求的实例讲解

 更新时间:2020年9月15日 18:34  点击:2115

一)RestTemplate简介

RestTemplate是HTTP客户端库提供了一个更高水平的API。主要用于Rest服务调用。

RestTemplate方法:

方法组 描述

getForObject

通过GET检索表示形式。

getForEntity

ResponseEntity通过使用GET 检索(即状态,标头和正文)。

headForHeaders

通过使用HEAD检索资源的所有标头。

postForLocation

通过使用POST创建新资源,并Location从响应中返回标头。

postForObject

通过使用POST创建新资源,并从响应中返回表示形式。

postForEntity

通过使用POST创建新资源,并从响应中返回表示形式。

put

通过使用PUT创建或更新资源。

patchForObject

通过使用PATCH更新资源,并从响应中返回表示形式。请注意,JDK HttpURLConnection不支持PATCH,但是Apache HttpComponents和其他支持。

delete

使用DELETE删除指定URI处的资源。

optionsForAllow

通过使用ALLOW检索资源的允许的HTTP方法。

exchange

前述方法的通用性强(且意见少的版本),在需要时提供了额外的灵活性。它接受RequestEntity(包括HTTP方法,URL,标头和正文作为输入)并返回ResponseEntity。

这些方法允许使用ParameterizedTypeReference而不是Class使用泛型来指定响应类型。

execute

执行请求的最通用方法,完全控制通过回调接口进行的请求准备和响应提取。

二)RestTemplate案例

第一步:创建一个maven项目,在pom.xml引入一个springboot的版本

pom.xml内容:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.oysept</groupId>
  <artifactId>spring_resttemplate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/>
  </parent>
 
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
  
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <mainClass>com.oysept.RestTemplateApplication</mainClass>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

application.yml配置:该配置就一个默认端口

server:

port: 8080

创建一个springboot启动类RestTemplateApplication

package com.oysept;
 
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
 
@SpringBootApplication
public class RestTemplateApplication {
 
  public static void main(String[] args) {
    new SpringApplicationBuilder(RestTemplateApplication.class).run(args);
  }
}

到此步骤时,可以先运行RestTemplateApplication中的main方法,检验springboot启动是否正常。

第二步:创建一个RestTemplate配置类并注入,因为在使用时,不提前注入ResttTemplate,在通过@Autowired使用会报RestTemplate找不到

package com.oysept.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
 
/**
 * 注册一个RestTemplate Bean, 否则直接通过@Autowired使用会报RestTemplate找不到
 * @author ouyangjun
 */
@Configuration
public class RestTemplateConfig {
 
  /**
   * 方式一: 默认是使用JDK原生java.net.HttpURLConnection请求
   * @return
   */
  @Bean(name = "restTemplate")
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }
 
  /**
   * 方式二: 使用apache http内置请求, 需要在pom.xml中引入相应的apache jar
   * 可以使用HttpClient,设置一些http连接池等信息
   * @return
   *
  @Bean(name = "restTemplate")
  public RestTemplate restTemplate() {
    return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
  }
   */
 
  /**
   * 方式三: 使用OkHttp内置请求, 需要在pom.xml中引入相应的OkHttp3 jar
   * 可以使用OkHttpClient,设置一些http连接池信息
   * @return
   *
  @Bean(name = "restTemplate")
  public RestTemplate restTemplate() {
    return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
  }
  */
}

第三步:创建一个VO类,用于测试入参和出参

package com.oysept.vo; 
public class MsgVO { 
  private String msgKey;
  private String msgValue;
 
  public String getMsgKey() {return msgKey;}
  public void setMsgKey(String msgKey) {this.msgKey = msgKey;}
 
  public String getMsgValue() {return msgValue;}
  public void setMsgValue(String msgValue) {this.msgValue = msgValue;}
 
  public String toString() {
    return "MsgVO [msgKey: "+this.msgKey+", msgValue: "+this.msgValue+"]";
  }
}

第四步:创建一个服务端接口,用于测试

package com.oysept.controller;
 
import java.util.ArrayList;
import java.util.List; 
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.oysept.vo.MsgVO;
 
/**
 * 服务端, 提供接口被调用
 * @author ouyangjun
 */
@RestController
public class ServerController {
 
  // 无参GET请求: http://localhost:8080/server/get
  @RequestMapping(value = "/server/get", method = RequestMethod.GET)
  public String get() {
    return "/server/get";
  }
 
  // 带参GET请求: http://localhost:8080/server/get/param?param=111222333444
  @RequestMapping(value = "/server/get/param", method = RequestMethod.GET)
  public String getParam(@RequestParam(value = "param") String param) {
    return "/server/get/param," + param;
  }
 
  // 路径中带参GET请求: http://localhost:8080/server/get/url/AAAA/BBBB
  @RequestMapping(value = "/server/get/url/{one}/{two}", method = RequestMethod.GET)
  public String getUrl(@PathVariable("one") String one, @PathVariable("two") String two) {
    return "/get/url/{one}/{two}," + one + "," + two;
  }
 
  // 无参GET请求, 返回List: http://localhost:8080/server/get/list
  @RequestMapping(value = "/server/get/list", method = RequestMethod.GET)
  public List<Object> getList() {
    List<Object> list = new ArrayList<Object>();
    list.add(11);
    list.add("AA");
    return list;
  }
 
  // 无参GET请求, 返回对象: http://localhost:8080/server/get/MsgVO
  @RequestMapping(value = "/server/get/MsgVO", method = RequestMethod.GET)
  public MsgVO getMsgVO() {
    MsgVO vo = new MsgVO();
    vo.setMsgKey("keyAAA");
    vo.setMsgValue("valueBBB");
    return vo;
  }
 
  // POST请求, 表单参数, application/x-www-form-urlencoded
  @RequestMapping(value = "/server/post/form", method = RequestMethod.POST, 
    consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  public MsgVO postForm(MsgVO msgVO) {
    System.out.println("msgKey: " + msgVO.getMsgKey() + ", msgValue: " + msgVO.getMsgValue());
    return msgVO;
  }
 
  // POST请求, JSON参数, application/json
  @RequestMapping(value = "/server/post/json", method = RequestMethod.POST, 
      consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
      produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public MsgVO postJson(@RequestBody MsgVO msgVO) {
    System.out.println("msgKey: " + msgVO.getMsgKey() + ", msgValue: " + msgVO.getMsgValue());
    return msgVO;
  }
}

第五步:创建一个测试服务端接口的API

import的类和注入的RestTemplate:

package com.oysept.controller; 
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
 
import com.oysept.vo.MsgVO;
 
/**
 * 客户端, 调用服务端提供的接口
 * @author ouyangjun
 */
@RestController
public class ClientController {
 
  // 使用默认请求方式
  @Autowired
  @Qualifier(value = "restTemplate")
  private RestTemplate restTemplate;
 
  // 在此处添加客户端测试代码
}

1、GET请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/get
@RequestMapping(value = "/client/get", method = RequestMethod.GET)
public String get() {
  // 无参GET请求
  String get = restTemplate.getForObject("http://localhost:8080/server/get", String.class);
  System.out.println("==>/server/get return: " + get);
 
  // 带参GET请求
  String getParam = restTemplate.getForObject("http://localhost:8080/server/get/param?param=111222333444", String.class);
  System.out.println("==>/server/get/param return: " + getParam);
 
  // 带参GET url请求
  String getUrlParam = restTemplate.getForObject("http://localhost:8080/server/get/url/{one}/{two}", String.class, "AAAA", "BBBB");
  System.out.println("==>/server/get/url/{one}/{two} return: " + getUrlParam);
 
  // 带参GET url请求
  Map<String, String> vars = new HashMap<String, String>();
  vars.put("one", "HHHH");
  vars.put("two", "EEEE");
  String getUrlVars = restTemplate.getForObject("http://localhost:8080/server/get/url/{one}/{two}", String.class, vars);
  System.out.println("==>/server/get/url/{one}/{two} return: " + getUrlVars);
 
  // 无参GET请求, 返回List
  @SuppressWarnings("unchecked")
  List<String> getList = restTemplate.getForObject("http://localhost:8080/server/get/list", List.class);
  System.out.println("==>/server/get/list return: " + getList);
 
  // GET请求, 返回对象
  ResponseEntity<MsgVO> entity = restTemplate.getForEntity("http://localhost:8080/server/get/MsgVO", MsgVO.class);
  System.out.println("==>/server/get/list return: " + entity.getBody());
  return "GET SUCCESS";
}

2、GET url中传参请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/get/request
// GET请求, url参数, 在表头中添加参数
@RequestMapping(value = "/client/get/request", method = RequestMethod.GET)
public String getRequest() {
  // url中参数
  Map<String, String> vars = new HashMap<String, String>();
  vars.put("one", "HHHH");
  vars.put("two", "EEEE");
 
  // 请求地址
  String uriTemplate = "http://localhost:8080/server/get/url/{one}/{two}";
  // 给URL地址encode转码
  URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(vars).toUri();
  // GET请求参数
  RequestEntity<Void> requestEntity = 
        RequestEntity.get(uri)
        .header("MyHeader", "aaabbbcccddd")
        .build();
  // 响应
  ResponseEntity<String> response = restTemplate.exchange(requestEntity, String.class);
  // 结果
  System.out.println("==>/get/request header: " + response.getHeaders().getFirst("MyHeader"));
  System.out.println("==>/get/request body: " + response.getBody());
  return "POST SUCCESS";
}

3、POST application/x-www-form-urlencoded表单传参请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/postForm
// POST请求, form表单入参
@RequestMapping(value = "/client/postForm", method = RequestMethod.GET)
public String postForm() {
  // uri
  String uriTemplate = "http://localhost:8080/server/post/form";
 
  // 设置请求头为form形式: application/x-www-form-urlencoded
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
  // 设置参数, 和MsgVO中变量名对应
  MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
  map.add("msgKey", "1234");
  map.add("msgValue", "TestTest");
 
  // 封装请求参数
  HttpEntity<MultiValueMap<String, String>> requestb = new HttpEntity<MultiValueMap<String, String>>(map,
  headers);
  ResponseEntity<String> response = restTemplate.postForEntity(uriTemplate, requestb, String.class);
  System.out.println("==>/server/post/form return: " + response.getBody());
  return "POST SUCCESS";
}

4、POST application/json JSON传参请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/postJson
// POST请求, JSON入参
@RequestMapping(value = "/client/postJson", method = RequestMethod.GET)
public String postJson() {
  // json入参
  MsgVO vo = new MsgVO();
  vo.setMsgKey("TTT");
  vo.setMsgValue("KKK");
 
  String uriTemplate = "http://localhost:8080/server/post/json";
  URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand().toUri();
 
  RequestEntity<MsgVO> requestEntity = 
      RequestEntity.post(uri)
      .header("Content-Type", "application/json; charset=UTF-8")
      .body(vo);
  
  ResponseEntity<MsgVO> response = restTemplate.exchange(requestEntity, MsgVO.class);
  System.out.println("==>/server/post/json return: " + response.getBody());
  return "POST SUCCESS";
}

项目结构图:

以上这篇SpringBoot RestTemplate GET POST请求的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • gin 获取post请求的json body操作

    这篇文章主要介绍了gin 获取post请求的json body操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-15
  • C#使用Http Post方式传递Json数据字符串调用Web Service

    这篇文章主要为大家详细介绍了C#使用Http Post方式传递Json数据字符串调用Web Service,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • 深入C#中get与set的详解

    本篇文章是对C#中的get与set进行了详细的分析介绍,需要的朋友参考下...2020-06-25
  • C#模拟http 发送post或get请求的简单实例

    下面小编就为大家带来一篇C#模拟http 发送post或get请求的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • idea out目录与target目录的区别详解

    这篇文章主要介绍了idea out目录与target目录的区别详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-08
  • 微信小程序 网络请求(GET请求)详解

    这篇文章主要介绍了微信小程序 网络请求(GET请求)详解的相关资料,需要的朋友可以参考下...2016-11-22
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • 解决HttpPost+json请求---服务器中文乱码及其他问题

    这篇文章主要介绍了解决HttpPost+json请求---服务器中文乱码及其他问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-22
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • C#使用post发送和接收数据的方法

    这篇文章主要介绍了C#使用post发送和接收数据的方法,涉及C#使用post收发数据的相关技巧,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • springboot多模块包扫描问题的解决方法

    这篇文章主要介绍了springboot多模块包扫描问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16