使用RestTemplate实现http调用

今天想实现 java 后端发送 formdata 上传文件,为了以后查找方便,特此记录下来

上一次使用 WebClient 实现远程调用 (一个非阻塞、响应式的HTTP客户端,它以响应式被压流的方式执行HTTP请求) 查看

现在使用的 RestTemplate

RestTemplate 是用于同步client端访问 Restful 服务的一个核心类

默认使用 JDK 提供的包去建立HTTP连接

  为每种 HTTP 请求都实现了相关的请求封装方法,根据HTTP的六个方法制定

HTTP methodRestTemplate methods
DELETE delete
GET getForObject
  getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
POST postForLocation
  postForObject
PUT put
any exchange
  execute

 

eg:后端实现文件上传  

  (1)public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)

    参数:

      url -> URI类型的请求路径

      request -> 请求体对象

      responseType -> 响应数据类型

    返回值:

      响应消息体的内容

复制代码
package com.example.hystrix.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;

@RestController
public class DemoController {

    @RequestMapping("/upload")
    public String upload() {

        String url = "http://localhost:2001/api/upload"; //上传的地址
        String filePath = "E:\\test\\test.dxf";

        RestTemplate rest = new RestTemplate();
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("files", resource); //MultipartFile的名称
        String rs = rest.postForObject(url, param, String.class);
        System.out.println(rs);
        return rs;
    }
}
复制代码

说明:

  exchange()方法跟上面的getForObject()、getForEntity()、postForObject()、postForEntity()等方法不同之处在于它可以指定请求的HTTP类型

  MultiValueMap 是 Map 的一个子类,它的一个 key 可以存储多个 value

  (2)public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType)

    参数:

      url -> URI类型的请求路径

        method-> 请求方式

      requestEntity-> 请求体

      responseType -> 响应数据类型

    返回值:

      Spring对HTTP请求响应的封装,包括了响应码、contentType、contentLength、响应消息体等

复制代码
package com.example.hystrix.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
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.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;

@RestController
public class DemoController {

    @RequestMapping("/upload")
    public String upload() {

        String url = "http://localhost:2001/api/upload"; //上传的地址
        String filePath = "E:\\test\\test.dxf";

        RestTemplate rest = new RestTemplate();
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("files", resource); //MultipartFile的名称
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param);
        ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
        String rs = responseEntity.getBody();
        System.out.println(rs);
        return rs;
    }
}
复制代码

说明:

  exchange()方法跟上面的getForObject()、getForEntity()、postForObject()、postForEntity()等方法不同之处在于它可以指定请求的HTTP类型

eg,其他

  发送Get请求

  (1)public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)

    参数:

      url -> URI类型的请求路径

      responseType -> 响应数据类型

      uriVariables-> URL变量

    返回值:

      Spring对HTTP请求响应的封装,包括了响应码、contentType、contentLength、响应消息体等

复制代码
package com.example.hystrix.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
public class DemoController {

    @RequestMapping("/test")
    public String test() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:2001/api/test?name={name}&text={text}";
        Map<String, String> params = new HashMap<>();
        params.put("name", "baby");
        params.put("text", "aaa");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, params);
        String response = responseEntity.getBody();
        return response;
    }
}
复制代码

  (2)public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)

    参数:

      url -> URI类型的请求路径

      responseType -> 响应数据类型

      uriVariables-> URL变量

    返回值:

      响应消息体的内容

复制代码
package com.example.hystrix.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
public class DemoController {

    @RequestMapping("/test")
    public String test() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:2001/api/test?name={name}&text={text}";
        Map<String, String> params = new HashMap<>();
        params.put("name", "baby");
        params.put("text", "aaa");
        String response = restTemplate.getForObject(url, String.class, params);

        return response;
    }
}
复制代码

  说明:

    url里使用name={name}的形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值

    只关注返回的消息体的内容,对其他信息都不关注,可以使用getForObject

posted @   慕尘  阅读(1237)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示