Spring的RestTemplate的使用

作为一名Java开发者,我们怎么都绕不开调用外部接口的场景,调用的方式要么是通过Http协议来调用,要么是通过RPC协议来调用,通过Http协议调用的话我们就需要用到Http的Api。比较常用的有Apache的HttpClient和原生的HttpURLConnection。这些Api都比较好用,但是我们今天要介绍一种更加好用API,Spring自带的RestTemplate,能力更强,使用更方便。

怎么用?

SpringBoot项目

SpringBoot项目中,只需要引入spring-boot-starter-web依赖就可以了,其实spring-boot-starter-web依赖也是SpringBoot项目必备的一个依赖。

	<dependency>
	    <groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

设置超时时间

引入依赖之后,就来开始使用吧,任何一个Http的Api我们都可以设置请求的连接超时时间,请求超时时间,如果不设置的话,就可能会导致连接得不到释放,造成内存溢出。这个是我们需要重点注意的点,下面就来看看RestTemplate如何来设置超时时间呢?我们可以在SimpleClientHttpRequestFactory类中设置这两个时间,然后将factory传给RestTemplate实例,设置如下:

@Configuration
public class RestTemplateConfig {
    /**
     * 服务器返回数据(response)的时间
     */
    private static final Integer READ_TIME_OUT = 6000;
    /**
     * 连接上服务器(握手成功)的时间
     */
    private static final Integer CONNECT_TIME_OUT = 6000;

    @Bean
    public RestTemplate restTemplate(){
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
        return new RestTemplate(requestFactory);
    }

    @Bean
    public HttpClient httpClient(){
        // 支持HTTP、HTTPS
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(100);
        connectionManager.setValidateAfterInactivity(2000);
        RequestConfig requestConfig = RequestConfig.custom()
                // 服务器返回数据(response)的时间,超时抛出read timeout
                .setSocketTimeout(READ_TIME_OUT)
                // 连接上服务器(握手成功)的时间,超时抛出connect timeout
                .setConnectTimeout(CONNECT_TIME_OUT)
                // 从连接池中获取连接的超时时间,超时抛出ConnectionPoolTimeoutException
                .setConnectionRequestTimeout(1000)
                .build();
        return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
    }
}

说完了RestTemplate的相关设置,下面就来看看平时我们用的最多两种请求方法:get方法和post方法吧。

GET请求

RestTemplate中提供的get请求的方法主要分为两类,一类是只返回请求体,一类是返回ResponseEntity对象,这个对象主要是包装了Http请求的响应状态status,响应头headers,和响应体body。后面我们会详细介绍。首先来看看getForObject方法。

返回业务对象类getForObject方法

getForObject方法的重载方法有如下三个:


/**
     方法一,直接将参数添加到url上面。
	 * Retrieve a representation by doing a GET on the specified URL.
	 * The response (if any) is converted and returned.
	 * <p>URI Template variables are expanded using the given URI variables, if any.
	 * @param url the URL  请求地址
	 * @param responseType the type of the return value  响应体的类型
	 * @param uriVariables the variables to expand the template 传入的参数
	 * @return the converted object
	 */
@Nullable
	<T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException;
/**
     方法二,通过Map来提交参数。
	 * Retrieve a representation by doing a GET on the URI template.
	 * The response (if any) is converted and returned.
	 * <p>URI Template variables are expanded using the given map.
	 * @param url the URL
	 * @param responseType the type of the return value
	 * @param uriVariables the map containing variables for the URI template
	 * @return the converted object
	 */
	@Nullable
	<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException;

	/**
	   方法三,用URI来请求。
	 * Retrieve a representation by doing a GET on the URL .
	 * The response (if any) is converted and returned.
	 * @param url the URL
	 * @param responseType the type of the return value
	 * @return the converted object
	 */
	@Nullable
	<T> T getForObject(URI url, Class<T> responseType) throws RestClientException;

下面定义了一个接口,用来测试上面三个方法的使用,这个接口有两个参数,分别是userId和userName。
根据传入的userId和userName来查询用户,如果可以查询的到的话,则返回查询到的用户,如果查询不到的话,则返回找不到数据。
响应体是JSON格式的。

 /**
     * get请求获取用户
     *
     * @param userName 用户名
     * @param userId 用户id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUser.do")
    public ResultData<User> getUserByName(
            @RequestParam(name = "userId",required = false) Integer userId,
            @RequestParam(name = "userName",required = false) String userName) {
        if (StringUtils.isAnyBlank(userName)) {
            return new ResultData<>(HttpStatus.BAD_REQUEST.value(), null, "参数不能为空");
        }
        List<User> userList = new ArrayList<>();
        for (int i = 1; i <= 2; i++) {
            User user = new User();
            user.setUserId(i);
            user.setUserName("张三" + i);
            user.setAge(20 + i);
            userList.add(user);
        }
        for (User user : userList) {
            if (userName.equals(user.getUserName()) && userId.equals(user.getUserId())) {
                return new ResultData(HttpStatus.OK.value(), user, "成功");
            }
        }
        return new ResultData<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), null, "找不到数据");
    }

下面我们就分别用那三个方法请求/getUser.do接口进行测试:

 @Test
    public void getForObjectTest() {
        String baseUrl = "http://localhost:8081/testRestTemplateApp/getUser.do";
       //方法一: 直接拼接参数,推荐使用
	   String url =baseUrl+"?userName=张三1&userId=1";
        ResultData resultData = restTemplate.getForObject(url, ResultData.class);
        System.out.println("*****GET直接拼接参数查询返回结果={}" + JSON.toJSONString(resultData));
        //方法一:传参替换,推荐使用
        url = baseUrl+"?userName={?}&userId={?}";
        resultData = restTemplate.getForObject(url, ResultData.class, "张三2",2);
        System.out.println("*****GET传参替换查询返回结果={}" + JSON.toJSONString(resultData));
        //方法一:传参替换,使用String.format,推荐使用
        url = baseUrl + String.format("?userName=%s&userId=%s", "张三2",2);
        resultData = restTemplate.getForObject(url, ResultData.class);
        System.out.println("******GET使用String.format查询返回结果={}" + JSON.toJSONString(resultData));
        //方法二:使用Map,不推荐使用
        url = baseUrl + "?userName={userName}&userId={userId}";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userName", "张三1");
        paramMap.put("userId",1);
        resultData = restTemplate.getForObject(url, ResultData.class, paramMap);
        System.out.println("******GET使用Map查询返回结果={}" + JSON.toJSONString(resultData));
        //方法三:使用URI,不推荐使用
        URI uri = URI.create(baseUrl+"?userName=%E5%BC%A0%E4%B8%891&userId=1");
        ResultData resultData1 = restTemplate.getForObject(uri, ResultData.class);
        System.out.println("******GET使用URI查询返回结果={}" + JSON.toJSONString(resultData1));
    }

运行结果如下:

在这里插入图片描述

需要注意的是:

      传参替换使用{?}来表示坑位,根据实际的传参顺序来填充,如下:

  url = baseUrl+"?userName={?}&userId={?}";
  resultData = restTemplate.getForObject(url, ResultData.class, "张三2",2);
  • 使用{xx}来传递参数时,这个xx对应的就是map中的key
 url = baseUrl + "?userName={userName}&userId={userId}";
 Map<String, Object> paramMap = new HashMap<>();
 paramMap.put("userName", "张三1");
 paramMap.put("userId",1);
  • 当响应头是application/json;charset=UTF-8格式的时候,返回的数据类型可以直接写String.class,如下
 String url ="http://localhost:8081/testRestTemplateApp/getUser.do?userName=张三1&userId=1";
  String resultData = restTemplate.getForObject(url, String.class);
  • 不推荐直接使用方法三传入URI,原因主要有如下两点: 1. 传入的参数包含中文时必须要转码,直接传中文会报400的错误,2. 响应的结果必须要跟接口的返回值保持一致,不然回报406的错误。
//userName不能直接传入张三1,不然会报400的错误
URI uri = URI.create(baseUrl+"?userName=%E5%BC%A0%E4%B8%891&userId=1");
//responseType不能传入String.class,不然会报406的错误
ResultData resultData1 = restTemplate.getForObject(uri, ResultData.class);

说完了getForObject,下面来看看getForEntity的方法,这三个方法跟上面的getForObject三个方法分别对应,只是返回值不同。

	<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)
			throws RestClientException;

	<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)
			throws RestClientException;

	<T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException;
  • 这里只列举一个参数拼接的方式来举例说明:
  String baseUrl = "http://localhost:8081/testRestTemplateApp/getUser.do";
  //参数拼接的方式
  String url =baseUrl+"?userName=张三1&userId=1";
  ResponseEntity<ResultData> entity = restTemplate.getForEntity(url, ResultData.class);
  System.out.println("*****参数拼接查询返回结果={}" + JSON.toJSONString(entity));
  • 运行后的结果如下:有响应头heads,有响应体body,有响应状态statusCodeValue等。
{"body":{"busCode":200,"data":{"userId":1,"userName":"张三1","age":21},"msg":"成功"},"headers":{"Content-Type":["application/json;charset=UTF-8"],"Transfer-Encoding":["chunked"],"Date":["Fri, 06 Mar 2020 05:42:08 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]},"statusCode":"OK","statusCodeValue":200}

POST 请求

说完了get请求相关的方法之后,接下来我们来看看post请求相关的方法,首先还是来看postForObject的三个重载方法。

	/**
	 * @param url the URL   请求地址
	 * @param request the Object to be POSTed (may be {@code null})  请求体,可以传入一个Bean对象,也可以传入HttpEntity对象,包装请求头
	 * @param responseType the type of the return value  响应对象的类型
	 * @param uriVariables the variables to expand the template 传入的参数
	 * @return the converted object 
	 * @see HttpEntity
	 */
	@Nullable
	<T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
			Object... uriVariables) throws RestClientException;
/**
	 * @param url the URL 请求地址
	 * @param request the Object to be POSTed (may be {@code null})  请求体,可以传入一个Bean对象,也可以传入HttpEntity对象,包装请求头
	 * @param responseType the type of the return value 响应对象的类型
	 * @param uriVariables the variables to expand the template 传入的map
	 * @return the converted object
	 * @see HttpEntity
	 */
	@Nullable
	<T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
			Map<String, ?> uriVariables) throws RestClientException;

	/**
	 * @param url the URL
	 * @param request the Object to be POSTed (may be {@code null})
	 * @param responseType the type of the return value
	 * @return the converted object
	 * @see HttpEntity
	 */
	@Nullable
	<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException;
				

还是用上面的/getUser.do接口进行测试。

    @Test
    public void testPostForObjectForForm() {
        String baseUrl = "http://localhost:8081/testRestTemplateApp/getUser.do";

        //方法一:表单提交
        MultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
        request.set("userName","张三1");
        request.set("userId",1);
        ResultData resultData = restTemplate.postForObject(baseUrl,request, ResultData.class);
        System.out.println("*****POST表单提交使用URI查询返回结果={}" + JSON.toJSONString(resultData));

        //方法二:使用Map
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userName", "张三2");
        paramMap.put("userId",2);
        resultData = restTemplate.postForObject(baseUrl,paramMap, ResultData.class);
        System.out.println("******POST使用Map查询返回结果={}" + JSON.toJSONString(resultData));

        //方法三:使用URI
        URI uri = URI.create(baseUrl);
        resultData = restTemplate.postForObject(uri,request, ResultData.class);
        System.out.println("******POST使用URI查询返回结果={}" + JSON.toJSONString(resultData));
    }

运行结果如下:

从运行结果我们可以看出,
如果传入的参数是MultiValueMap类型的对象是,Spring会通过AllEncompassingFormHttpMessageConverter转换器来将参数通过表单提交。
如果直接传入一个Map对象,则会通过MappingJackson2HttpMessageConverter转换器对参数进行转换。
说完了表单提交,下面我们看看另外一种场景,如下,这个接口是一个保存用户数据的接口,参数需要格式化后放在请求体中。

    @ResponseBody
    @PostMapping("/addUserJSON.do")
    public ResultData<Boolean> addUserJSON(@RequestBody User user) {
        if (user == null) {
            return new ResultData<>(HttpStatus.BAD_REQUEST.value(), null, "参数不能为空");
        }
        return new ResultData<>(HttpStatus.OK.value(),true,"保存成功");
    }

当我们需要调用接口是通过@RequestBody来接受参数时,也就是需要传入一个JSON对象,我们该如何请求呢?我们调用可以postForObject可以直接传入User对象, 也可以将请求头设置成application/json,然后将User对象序列化,代码如下所示:

    @Test
    public void testPostForObject() {
        String baseUrl = "http://localhost:8081/testRestTemplateApp/addUserJSON.do";
        User user = new User();
        user.setUserName("李四");
        user.setAge(23);
        //第一种方式:不传入JSON的参数,不设置请求头
        ResultData resultData = restTemplate.postForObject(baseUrl, user, ResultData.class);
        System.out.println("*********不序列化传入参数请求结果={}" + JSON.toJSONString(resultData));
        //第二种方式:传入JSON类型的参数,设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(JSON.toJSONString(user),headers);
        resultData = restTemplate.postForObject(baseUrl, httpEntity, ResultData.class);
        System.out.println("*********序列化参数请求结果={}" + JSON.toJSONString(resultData));
    }

第一种方式是由于Spring内部的MappingJackson2HttpMessageConverter会将参数进行序列化并请求接口
第二种方式是直接设置好请求头为application/json,并将参数序列化。所以就不需要通过MappingJackson2HttpMessageConverter进行转换。比较推荐
运行结果如下:

postForEntity方法在此就不在赘述了。
说完了,get请求的相关方法和post请求的相关方法,接下来我们来看看另外一类方法

postForLocation

postForLocation的定义是POST 数据到一个URL,返回新创建资源的URL
同样提供了三个方法,分别如下,需要注意的是返回结果为URI对象,即网络资源

public URI postForLocation(String url, @Nullable Object request, Object... uriVariables)
		throws RestClientException ;

public URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables)
		throws RestClientException ;

public URI postForLocation(URI url, @Nullable Object request) throws RestClientException ;

这类接口主要应用在需要跳转页面的请求,比如,登录,注册,支付等post请求,请求成功之后需要跳转到成功的页面。这种场景下我们可以使用postForLocation了,提交数据,并获取放回的URI,一个测试如下:
首先mock一个接口

    @ResponseBody
    @RequestMapping(path = "loginSuccess")
    public String loginSuccess(String userName, String password) {
        return "welcome " + userName;
    }

    /**
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(path = "login", method = {RequestMethod.GET, RequestMethod.OPTIONS, RequestMethod.POST}
            ,produces = "charset/utf8")
    public String login(@RequestParam(value = "userName", required = false) String userName,
                       @RequestParam(value = "password", required = false) String password) {
        return "redirect:/loginSuccess?userName=" + userName + "&password=" + password + "&status=success";
    }

测试请求是:

    @Test
    public void testPostLocation() {
        String url = "http://localhost:8081/testRestTemplateApp/login";
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("userName", "bob");
        paramMap.add("password", "1212");
        URI location = restTemplate.postForLocation(url, paramMap);
        System.out.println("*******返回的数据=" + location);
    }

运行结果如下:

在这里插入图片描述

介绍完了restTemplate的常用方法,但是,我们或许会感觉到restTemplate的方法太多了,调用起来不太方便,为了使用方便,我们就对restTemplate做一个封装。代码如下所示:主要封装成了四个方法,一个是通过get请求的方法,一个是通过表单提交的post请求方法,一个是通过json提交的post请求方法,最后就是上传图片的方法。

@Component
public class RestTemplateProxy {
    @Autowired
    private RestTemplate restTemplate;

    /**
     *
     * @param url 请求地址
     *        参数可以通过 http://localhost:8888/juheServer/juhe/info/queryCustomer.do?taxNo=92330424MA29G7GY5W
     *            或者 http://localhost:8888/juheServer/juhe/info/queryCustomer.do+String.format("?taxNo=%s&order=%s", "92330424MA29G7GY5W","1212121212");
     * @param responseType 返回值的类型
     * @return
     * @author xiagwei
     * @date 2020/3/5 5:28 PM
     *
     */
    public <T> T getForObject(String url, Class<T> responseType) {
        return restTemplate.getForObject(url, responseType);
    }

    /**
     * 通过json的方式请求服务,不需要将数据格式化,直接将请求对象传入即可
     * 可以是map,可以是一个bean
     * @param url 请求接口
     * @param requestParam 请求实体
     * @param responseType 返回对象的clazz
     * @return 
     * @author xiagwei
     * @date 2020/3/5 5:36 PM
     */ 
    public <T> T postForObjectJSON(String url, Object requestParam,Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(requestParam, headers);
        return restTemplate.postForObject(url, httpEntity, responseType);
    }   
    
    /**
     * 通过Form表单的方式提交
     * @param url 请求接口
     * @param requestParam 请求实体,可以是一个实体,也可以一个map
     * @param responseType 返回对象的clazz
     * @return 
     * @author xiagwei
     * @date 2020/3/5 5:42 PM
     */ 
    public <T> T postForObjectForm(String url, @NotNull Object requestParam, Class<T> responseType) {
        MultiValueMap<String, Object> valueRequestMap = creatValueMap(requestParam);
        return restTemplate.postForObject(url, valueRequestMap, responseType);
    }

    /**
     * 图片上传
     *
     * @param url  请求地址
     * @param body 请求体
     *           MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                 body.add("uploadFile", new FileSystemResource(ImageUtil.downloadImgByUrl(url)));
     * @param responseType 返回结果的clazz对象
     * @return
     * @author xiagwei
     * @date 2020/3/5 6:05 PM
     */
    public <T> T uploadImg(@NotNull String url, @NotNull  MultiValueMap<String, Object> body,Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body,headers);
        return restTemplate.postForObject(url,requestEntity,responseType);
    }


    private MultiValueMap creatValueMap(Object requestParam) {
        MultiValueMap<String, Object> valueRequestMap = new LinkedMultiValueMap<>();
        Map<String, Object> param = null;
        if (requestParam instanceof Map) {
            param = (Map<String, Object>) requestParam;
        } else {
            param = BeanUtil.beanToMap(requestParam);
        }
        for (String key : param.keySet()) {
            valueRequestMap.add(key, param.get(key));
        }
        return valueRequestMap;
    }
}

这里需要重点说下,图片上传的方法,上传图片的话,我们一定要把请求头设置成multipart/form-data,然后其余的参数通过MultiValueMap来设置。

    public <T> T uploadImg(@NotNull String url, @NotNull  MultiValueMap<String, Object> body,Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body,headers);
        return restTemplate.postForObject(url,requestEntity,responseType);
    }

总结

本文主要介绍了restTemplate类的使用,首先介绍了需要引入的依赖,然后介绍了如何设置超时时间,接着就是介绍了restTemplate中get请求相关的方法和post请求相关的方法,以及这些方法如何调用。最后就是对常用的请求方法做了一个封装。希望对读者朋友们有所帮助。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring RestTemplateSpring框架中的一个重要组件,用于简化HTTP请求的发送。使用RestTemplate可以实现对RESTful Web服务的访问,支持GET、POST、PUT、DELETE等常见的HTTP请求方法。 下面是Spring RestTemplate的一些基本使用方法: 1. 创建RestTemplate实例: ```java RestTemplate restTemplate = new RestTemplate(); ``` 2. 发送GET请求: ```java String url = "http://example.com/users/{userId}"; ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, userId); ``` 3. 发送POST请求: ```java String url = "http://example.com/users"; User user = new User(); ResponseEntity<User> response = restTemplate.postForEntity(url, user, User.class); ``` 4. 发送PUT请求: ```java String url = "http://example.com/users/{userId}"; User user = new User(); restTemplate.put(url, user, userId); ``` 5. 发送DELETE请求: ```java String url = "http://example.com/users/{userId}"; restTemplate.delete(url, userId); ``` RestTemplate还有很多其他的方法,更详细的使用方法可以参考Spring官方文档。 ### 回答2: Spring RestTemplateSpring框架提供的用于处理RESTful请求的模板类。它封装了底层的HTTP通信细节,提供了简化的API,使得开发者可以更方便地发送HTTP请求和接收响应。 在使用RestTemplate之前,我们首先需要在项目的依赖中引入Spring的web模块,因为RestTemplate是web模块的一部分。 使用RestTemplate发送HTTP请求的步骤如下: 1. 创建一个RestTemplate对象。可以直接通过new关键字创建,也可以通过Spring的依赖注入方式获取。 2. 选择合适的请求方法,并设置请求的URL和请求参数。RestTemplate提供了多种请求方法,如GET、POST等。我们可以通过参数的形式传递URL,并可以使用Map或对象封装请求参数。 3. 发送请求,并接收响应。可以调用RestTemplate的exchange()方法来发送请求,并通过ResponseEntity来接收响应。exchange方法可以指定请求方法、URL、请求体、请求头等信息,并可以通过参数化类型来指定响应的类型。 4. 解析响应。根据实际需要,我们可以使用ResponseEntity的getBody()方法获取响应的主体内容,并进行进一步的解析。 需要注意的是,使用RestTemplate发送请求时,我们可以自己编写请求头、请求体等信息,也可以通过使用RestTemplate提供的辅助方法来简化请求的构建。此外,RestTemplate还提供了异常处理和重试机制,可以更好地处理异常情况。 总的来说,Spring RestTemplate提供了简洁易用的API,帮助我们快速发送HTTP请求和处理响应,节省了开发时间和精力。它是Spring框架中非常重要的一部分,值得开发者深入学习和掌握。 ### 回答3: Spring RestTemplateSpring框架中的一个HTTP访问客户端工具,它可以方便地进行HTTP请求的发送和响应的处理。 在使用RestTemplate之前,首先需要引入相关的依赖。在Maven项目中,可以通过在pom.xml文件中添加以下依赖来使用RestTemplate: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 引入依赖后,可以通过如下方式创建一个RestTemplate对象: ``` RestTemplate restTemplate = new RestTemplate(); ``` 之后就可以使用RestTemplate对象来发送HTTP请求了。RestTemplate提供了多种发送请求的方法,例如getForObject()、postForObject()等。 使用getForObject()方法发送GET请求并接收响应: ``` String url = "http://api.example.com/data"; String response = restTemplate.getForObject(url, String.class); ``` 使用postForObject()方法发送POST请求并接收响应: ``` String url = "http://api.example.com/data"; String requestBody = "param1=value1&param2=value2"; String response = restTemplate.postForObject(url, requestBody, String.class); ``` RestTemplate还提供了其他一些方法,例如exchange()方法可以发送更复杂的请求,并接收带有响应头和状态码等信息的响应对象。 在使用RestTemplate发送请求时,可以通过设置请求头、请求体、URI参数等来定制请求。可以通过如下方式来设置请求头: ``` HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer token"); HttpEntity<String> requestEntity = new HttpEntity<>(headers); ``` 可以通过如下方式来设置请求体: ``` MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("param1", "value1"); requestBody.add("param2", "value2"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody); ``` 可以通过如下方式来设置URI参数: ``` String url = "http://api.example.com/data?param1={param1}&param2={param2}"; Map<String, String> uriVariables = new HashMap<>(); uriVariables.put("param1", "value1"); uriVariables.put("param2", "value2"); String response = restTemplate.getForObject(url, String.class, uriVariables); ``` 总结来说,Spring RestTemplate是一个用于发送和处理HTTP请求的方便工具,通过引入相关依赖并创建RestTemplate对象,可以使用它发送不同类型的HTTP请求,并对响应进行处理。通过设置请求头、请求体、URI参数等,可以对请求进行定制。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值