restspring-bootresttemplaterestful-urlmedia-type

Invalid token character '/' in org.springframework.http.MediaType


I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat;

I want to create this MediaType

MediaType mediaType = new MediaType("application/vnd.bonanza+xml");

that in PostMan works fine, but not in RestTemplate

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816)
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
    at com.ideefecloud.IdeefeCloudApplication.main(IdeefeCloudApplication.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: Invalid token character '/' in token "application/vnd.bonanza+xml"

Solution

  • You are may be using the wrong constructor. this constructor takes only type as arguments and treats subtype as *

    Change:

    MediaType mediaType = new MediaType("application/vnd.bonanza+xml");
    

    To:

    MediaType mediaType = MediaType.valueOf("application/vnd.bonanza+xml");
    

    valueOf

    public static MediaType valueOf(String value)

    Parse the given String value into a MediaType object, with this method name following the 'valueOf' naming convention (as supported by ConversionService.

    Parameters:

    value - the string to parse

    Throws:

    InvalidMediaTypeException - if the media type value cannot be parsed

    OR:

    MediaType mediaType = new MediaType("application", "vnd.bonanza+xml");
    

    MediaType(String type, String subtype)

    Create a new MediaType for the given primary type and subtype.

    OR:

    MediaType mediaType = MediaType.yourType;