How to preserve string ("/") while sending api request as part of JSONObject

487 views Asked by At

I am trying to send below Jsonobject as request parameter to rest API.

{ "date": "2022-01-01", "value": [    "TST/USED" ] }

Value field contains the list of values, but when I add the value in this format as part of request it replaces string / to \/ due to which the request is not processing and it throws 415 : [no body] exception.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION, "Bearer " + token);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

JSONObject req = new JSONObject();
req.put("date",  "2022-01-01");
req.put("value", "TST/USED");

HttpEntity<Object> object = new HttpEntity<>(req.toString(), headers);

Object response = restTemplate.exchange(apiUrl, HttpMethod.POST, object, Object.class)
                              .getBody();
1

There are 1 answers

0
Juan On

I don't see the issue you mention, here is what I am running:

Main application with Spring boot and a RestTemplate bean.

package com.so.so72424428;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class So72424428Application {

    public static void main(String[] args) {
        SpringApplication.run(So72424428Application.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
    
}

An api to test:

package com.so.so72424428;

import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiEndPoint {
    
    @PostMapping(path = "/test-api", consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
    public String echo (@RequestBody String jsonMessage) {
        return jsonMessage;
    }

}

A class to run your code:

package com.so.so72424428;

import java.util.Arrays;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class So72424428 implements CommandLineRunner {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void run(String... args) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        //headers.add(AUTHORIZATION, "Bearer " + token);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);

        JSONObject req = new JSONObject();
        req.put("date",  "2022-01-01");
        req.put("value", "TST/USED");
        
        log.info(req.toString());

        HttpEntity<Object> object = new HttpEntity<>(req.toString(), headers);

        String apiUrl = "http://localhost:8080/test-api";
        
        Object response = restTemplate.exchange(apiUrl, HttpMethod.POST, object, Object.class)
                                      .getBody();
        log.info(response.toString());
    }

}

When I run the code I print out the content of the req variable: {"date":"2022-01-01","value":"TST/USED"}

Also after round trip of the request I print out the response: {date=2022-01-01, value=TST/USED}

This is the log:

2022-05-29 13:39:24.416  INFO 32332 --- [  restartedMain] com.so.so72424428.So72424428Application  : Starting So72424428Application using Java 15.0.2 on ...)
2022-05-29 13:39:24.418  INFO 32332 --- [  restartedMain] com.so.so72424428.So72424428Application  : No active profile set, falling back to 1 default profile: "default"
2022-05-29 13:39:24.462  INFO 32332 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-05-29 13:39:24.462  INFO 32332 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-05-29 13:39:25.310  INFO 32332 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-05-29 13:39:25.320  INFO 32332 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-05-29 13:39:25.320  INFO 32332 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-05-29 13:39:25.387  INFO 32332 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-05-29 13:39:25.388  INFO 32332 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 925 ms
2022-05-29 13:39:25.716  INFO 32332 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-05-29 13:39:25.760  INFO 32332 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-05-29 13:39:25.768  INFO 32332 --- [  restartedMain] com.so.so72424428.So72424428Application  : Started So72424428Application in 1.678 seconds (JVM running for 2.616)
2022-05-29 13:39:25.778  INFO 32332 --- [  restartedMain] com.so.so72424428.So72424428             : {"date":"2022-01-01","value":"TST/USED"}
2022-05-29 13:39:25.869  INFO 32332 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-05-29 13:39:25.869  INFO 32332 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-05-29 13:39:25.870  INFO 32332 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
2022-05-29 13:39:25.921  INFO 32332 --- [  restartedMain] com.so.so72424428.So72424428             : {date=2022-01-01, value=TST/USED}
2022-05-29 13:39:33.346  INFO 32332 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.

As you can see there is no backslash, nor no issue for completing the request.