RestTemplate服务之间传递数据-SpringBoot

本文详细介绍了在SpringSecurity环境下,如何通过RestTemplate实现服务间数据传递,包括如何正确设置请求头以携带Token,确保数据调用的安全性和正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、调用方:

代码

/**
* 描述: 封装的RestTemplate方法。
* url: 被调用方接口的URL.
* paramJson: 需要传递的参数数据, 这里传输的是list,使用jackson转换了.
* request: HttpServletRequest需要使用此参数设置Header和传输的数据.
*/
public void put(String url, String paramJson, HttpServletRequest request) throws JsonProcessingException {
        HttpEntity<String> requestEntity = setHttpHeader(request, paramJson);
        restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
  }

/**
* 描述: 封装的Http Header方法。
* url: 被调用方接口的URL.
* json: 需要传输的数据.
*/
private HttpEntity<String> setHttpHeader(HttpServletRequest request, String json) throws JsonProcessingException {
        String authorization = request.getHeader("Authorization");  //使用了Spring security,所以,需要设置token.
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "*/*");
        headers.add("Content-Type", "application/json");
        headers.add("Authorization", authorization);

        return new HttpEntity<>(json, headers);
    }

二、被调用方:

代码

/**
* 描述: 使用RequestBody接收传递过来的数据,使用jackson,进行反序列化.得到需要的数据.
*/
public void putTest(@RequestBody String ids) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<String> beanList = mapper.readValue(ids, new TypeReference<List<String>>() {});
    }

三、总结:

1. 对于项目中使用了Spring security,就会对于所有的API都保护起来,没有对应Token,是无法访问的,使用RestTemplate去访问其他的服务的时候,Token不会传递,需要我们对于请求头,再次添加token,才能保证调用数据的正确性。这是刚刚项目中的问题,若有更好的解决方法和问题,请大家包含和提问啦。。。

### Spring Boot 中使用 `JSONObject` 进行 HTTP 请求的数据递 在 Spring Boot 应用程序中,可以利用 `RestTemplate` 结合 `org.json.JSONObject` 来构建和解析 JSON 格式的请求体。下面展示了一个具体的例子来说明如何实现这一点。 #### 创建并配置 RestTemplate 实例 为了简化网络调用过程中的某些操作(比如统一处理超时),通常会自定义 `RestTemplate` 的 Bean 定义: ```java import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` #### 构建 POST 请求携带 JSON 数据 当需要向服务器端提交复杂结构化的数据时,可以通过创建一个 `JSONObject` 对象并将它作为参数入到 `postForEntity()` 或者其他合适的方法里去完成这个动作: ```java import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class JsonPostService { private final RestTemplate restTemplate; @Autowired public JsonPostService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public void sendJsonData(String url){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); JSONObject jsonRequest = new JSONObject(); jsonRequest.put("name", "John"); jsonRequest.put("age", 30); HttpEntity<String> entity = new HttpEntity<>(jsonRequest.toString(), headers); ResponseEntity<String> response = restTemplate.postForEntity(url, entity , String.class ); System.out.println(response.getBody()); } } ``` 这段代码展示了怎样通过 `HttpHeaders` 设置合适的 Content-Type 头信息,并且把 `JSONObject` 转换成字符串形式放入 `HttpEntity` 中以便于输给目标服务[^1]。 对于 PUT 和 DELETE 类型的操作也可以采用类似的模式来进行编码;主要区别在于所使用的具体 API 函数不同而已。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值