RestTemplate的基本使用之postForObject()

RestTemplate的基本使用之postForObject()

1. post请求的基本调用

原始接口(生产者)

package com.zk.datastruct.controller;


import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RequestMapping("/producer")
@RestController
@CrossOrigin
public class ProducerController {

    @PostMapping("/execute")
    public JSONObject execute(@RequestBody Map<String, String> map) {
//        处理正常业务代码
        return new JSONObject();
    }

}

调用接口(消费者)

package com.zk.datastruct.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

@RequestMapping("/consumer")
@RestController
@CrossOrigin
public class ConsumerController {

    @PostMapping("/invokeExecute")
    public JSONObject invokeExecute(){
//        获取RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

//        设置请求头,请求类型为json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

//        设置请求参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", "zhangsan");

        //用HttpEntity封装整个请求报文
        HttpEntity<HashMap<String, Object>> request = new HttpEntity<>(map, headers);

//        开始调用
//        参数1:目标请求地址
//        参数2:请求体
//        参数3:目标请求接口的返回值类型(execute接口的返回值类型)
        JSONObject result = restTemplate.postForObject("http://192.168.12.12:8080/test/producer/execute", request, JSONObject.class);

        return result;
    }

}

2. 文件类型的调用方式

原始接口(生产者)

package com.zk.datastruct.controller;


import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RequestMapping("/producer")
@RestController
@CrossOrigin
public class ProducerController {

    @PostMapping("/upload")
    public JSONObject upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)  {
//        处理文件上传业务代码
        return new JSONObject();
    }

}

调用接口(消费者)

package com.zk.datastruct.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;

@RequestMapping("/consumer")
@RestController
@CrossOrigin
public class ConsumerController {

    @PostMapping("/invokeUpload")
    public JSONObject invokeUpload(){
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        File file = new File("/Users/zk/Downloads/readme.txt");
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", new FileSystemResource(file));
        form.add("filename",file.getName());

        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        JSONObject result = restTemplate.postForObject("http://192.168.12.12:8080/test/producer/upload", files, JSONObject.class);
        return result;
    }
}

3. 代码优化

在一个成熟的项目中,其中RestTemplate对象和HttpHeaders对象就不应该再new出来了,应使用spring工厂自动创建,使用时注入即可。包括目标URL,也不应该硬编码在程序中写死,应写在application.yml配置文件中,用到时取出即可,这样也方便进行管理和调试。

applicationi.yml配置文件

rest-template:
  upload-url: http://192.168.12.12:8080/test/producer/upload
  execute-url: http://192.168.12.12:8080/test/producer/execute

创建配置类

@Component
public class RestTemplateConfig {

    @Bean
    RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @Bean
    HttpHeaders getHttpHeaders(){
        return new HttpHeaders();
    }

}

修改控制器类

package com.zk.datastruct.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;

@RequestMapping("/consumer")
@RestController
@CrossOrigin
public class ConsumerController {

    @Value("${rest-template.upload-url}")
    private String uploadUrl;

    @Value("${rest-template.execute-url}")
    private String executeUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HttpHeaders headers;


    @PostMapping("/invokeExecute")
    public JSONObject invokeExecute(){

//        设置请求头,请求类型为json
        headers.setContentType(MediaType.APPLICATION_JSON);

//        设置请求参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", "zhangsan");

        //用HttpEntity封装整个请求报文
        HttpEntity<HashMap<String, Object>> request = new HttpEntity<>(map, headers);

//        开始调用
//        参数1:目标请求地址
//        参数2:请求体
//        参数3:目标请求接口的返回值类型(execute接口的返回值类型)
        JSONObject result = restTemplate.postForObject(executeUrl, request, JSONObject.class);

        return result;
    }

    @PostMapping("/invokeUpload")
    public JSONObject invokeUpload(){

        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        File file = new File("/Users/zk/Downloads/readme.txt");
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", new FileSystemResource(file));
        form.add("filename",file.getName());

        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        JSONObject result = restTemplate.postForObject(uploadUrl, files, JSONObject.class);
        return result;
    }
    
}

  • 23
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值