You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否修改RestTemplate返回的ResponseEntity响应体后重新返回?

问题背景

我需要向前端返回JSON文件内容,计划在内容发送至前端前对其进行修改:在内容首尾分别添加[和]符号。做此修改的原因是目标JSON文件存在multiple json root elements(多JSON根元素)的格式问题。

当前通过如下方式获取接口响应结果:

result = restTemplate.executeRequest(HttpMethod.GET, String.class);
//change Body and put it back in result

核心问题

是否可以修改ResponseEntity中的响应体内容,再将修改后的响应对象正常返回?


现有业务源码

业务接口实现代码:

public ResponseEntity<String> getScalityObject(String chainCode, String dataCenter, String path, String byteRange) {
    Map<String, Object> queryParams = new HashMap<>();
    if (dataCenter != null && !dataCenter.isEmpty()) {
        queryParams.put("dataCenter", dataCenter);
    }
    if (byteRange != null && !byteRange.isEmpty()) {
        queryParams.put("byteRange", byteRange);
    }
    String decodedStr = URLDecoder.decode(path);
    queryParams.put("path", decodedStr);

    reservationService.setContext(
            RESA_INTERNAL_SERVICE_NAME,
            queryParams,
            "/chains/{chainCode}/objects/file",
            chainCode);
    restTemplate.setServiceDefinition(reservationService);
    
    ResponseEntity<String> result;
    try {
        result = restTemplate.executeRequest(HttpMethod.GET, String.class);
        //Change responseBody here
        return result;
    } catch (IOException e) {
        e.printStackTrace();
        result = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return result;
}

自定义RestTemplate请求执行逻辑:

public <T> ResponseEntity<T> executeRequest(HttpMethod method, Class<T> responseType) throws IOException {

        if (this.serviceDefinition == null) {
            throw new IllegalArgumentException("You haven't provided any service definition for this call. " +
                "Are you sure you called the right method before using this Amadeus Rest Template?");
        }

        // Resolve the URI
        URI url = this.serviceDefinition.getUriComponents().toUri();

        // Add the extra headers if necessary
        HttpHeaders headers = new HttpHeaders();
        if (this.serviceDefinition.getHeaders() != null) {
            for(Map.Entry<String,String> headerSet : this.serviceDefinition.getHeaders().entrySet()) {
                headers.put(headerSet.getKey(), Arrays.asList(headerSet.getValue()));
            }
        }
        HttpEntity entity = new HttpEntity(headers);
        ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);

        RequestCallback requestCallback = httpEntityCallback(entity, responseType);
        ClientHttpResponse response = null;
        try {
            ClientHttpRequest request = createRequest(url, method);
            if (requestCallback != null) {
                requestCallback.doWithRequest(request);
            }
            response = request.execute();
            return (responseExtractor != null ? responseExtractor.extractData(response) : null);
        }
        catch (IOException ex) {
            throw ex;
        }
        finally {
            if (response != null) {
                response.close();
            }
        }

    }

解决方案

可以修改,ResponseEntity支持基于原有响应的状态码、头信息,替换响应体后构建新实例返回,不需要改动底层executeRequest逻辑,直接在业务层拿到响应结果后处理即可。

具体实现逻辑:

  • 先校验响应状态、响应体非空,避免空指针,也防止空响应被拼接成无效的[]
  • 取出原始响应字符串,去除首尾空白后在首尾拼接[和]完成JSON格式修正
  • 复用原响应的状态码、响应头,传入修改后的响应体构建新的ResponseEntity返回

对应代码修改片段:

try {
    result = restTemplate.executeRequest(HttpMethod.GET, String.class);
    String originalBody = result.getBody();
    if (originalBody == null || originalBody.isBlank()) {
        return result;
    }
    // 修正多根节点的JSON格式问题
    String fixedBody = "[" + originalBody.trim() + "]";
    // 复用原状态码、响应头返回修改后的结果
    return new ResponseEntity<>(fixedBody, result.getHeaders(), result.getStatusCode());
} catch (IOException e) {
    e.printStackTrace();
    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}

注意:一般Web框架会自动根据返回的新响应体重算Content-Length,不需要手动修改头信息。如果遇到响应长度不匹配的问题,可手动更新headers里的Content-Length为新body的对应字节长度。


内容的提问来源于stack exchange,提问作者Hani Gotc Reinstate Monica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:39:39