Springboot中RestTemplate使用总结

1、RestTemplate基本使用

RestTemplate的POST请求常用的两个主要方法为:
1、postForObject()
2、postForEntity()

二者的主要区别:
postForObject()返回值是HTTP协议的响应体。
postForEntity()返回的是ResponseEntity,ResponseEntity是对HTTP响应的封装,除了包含响应体,还包含HTTP状态码、contentType、contentLength、Header等信息。

postForObject的用法

 	// 请求地址
   String url = "http://jsonplaceholder.typicode.com/posts";
   // 请求头设置,x-www-form-urlencoded格式的数据
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
   //提交参数设置
   MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
   map.add("title", "zimug 发布文章第二篇");
   map.add("body", "zimug 发布文章第二篇 测试内容");
   // 组装请求体
   HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
   // 发送post请求,并打印结果,以String类型接收响应结果JSON字符串
   String result = restTemplate.postForObject(url, request, String.class);
   System.out.println(result);

postForEntity的用法

    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("multipart/form-data");
    // 设置请求的格式类型
    headers.setContentType(type);
    FileSystemResource fileSystemResource = new FileSystemResource(path);
    MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
    form.add("name", fileSystemResource);
    HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
    ResponseEntity<TopicFileResponse> responseResponseEntity = restTemplate.postForEntity(url, files, TopicFileResponse.class);
    TopicFileResponse body = responseResponseEntity.getBody();
    return body;

参考博客
【1】精讲RestTemplate第4篇-POST请求方法使用详解
【2】使用restTemplate上传文件MultipartFile

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值