Home > Back-end >  Is It possible to change the content of the Body of a responseEntity
Is It possible to change the content of the Body of a responseEntity

Time:07-12

I am trying to return the content of a Json file. But I want to modify before sending it to the front end. I want to add "[" and "]" at the beginning and end of the file. I am doing that because the json file has multiple json root elements.

Like for example extract the result as illustrated in

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

Question

Is it possible to change the body of the response and put it back in ResponseEntity?


Source Code

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;
}

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();
            }
        }

    }

CodePudding user response:

One of the way which I can think of is :

ResponseEntity<String> result = restTemplate.executeRequest(HttpMethod.GET, String.class);

StringBuilder builder = new StringBuilder(result.getBody());
... //do your transformation to stringbuilder reference.
result = ResponseEntity.status(result.getStatusCode()).body(builder.toString());

Another way if you want to avoid this is to return String response from your executeRequest & modify that response before creating ResponseEntity.

CodePudding user response:

Try this:

  1. Create your own HttpMessageConverter, implementing:

    public interface HttpMessageConverter<T> {
    
     // Indicates whether the given class can be read by this converter.
     boolean canRead(Class<?> clazz, MediaType mediaType);
    
     // Indicates whether the given class can be written by this converter.
     boolean canWrite(Class<?> clazz, MediaType mediaType);
    
     // Return the list of {@link MediaType} objects supported by this converter.
     List<MediaType> getSupportedMediaTypes();
    
     // Read an object of the given type form the given input message, and returns it.
     T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
         throws IOException, HttpMessageNotReadableException;
    
     // Write an given object to the given output message.
     void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
         throws IOException, HttpMessageNotWritableException;
    }
    
  2. Register the custom converter into your restTemplate object:

    String url = "url";
    
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate();
    
    // Add the String message converter
    restTemplate.getMessageConverters().add(new YourConverter());
    
    // Make the HTTP GET request, marshaling the response to a String
    String result = restTemplate.getForObject(url, String.class);
    
  • Related