Kevin Kevin - 1 month ago 14
Java Question

415 unsupported mediaType in POST request

Was reading around and a lot of the issues others were having were Spring, Gradle, or something else. It seems that Postman does not like my request that I'm giving to my

POST
method.

Error:

b>description</b>
<u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (Unsupported Media Type).</u>


Body from Postman:

{
"firstName": "firstName",
"lastName": "lastName",
"dob": "12/12/2012",
"address": "123 main st."
}


POST in question:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/createQuery")
public Response createQuery(ApplicationInfo info) throws IOException {
String queryString =createStringFromJSON(info,true);
queryMap.put(""+countId,queryString);
countId++;
ObjectMapper objectMapper = new ObjectMapper();
String json = "";
try {
json = objectMapper.writeValueAsString(queryMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
} return Response.ok(json,MediaType.APPLICATION_JSON_TYPE).entity(json).build();
}


Incredibly complex ApplicationInfo Object:

public class ApplicationInfo

{
String firstName;
String lastName;
String dob;
String address;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getDob() {
return dob;
}

public void setDob(String dob) {
this.dob = dob;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}


Hopefully someone more experienced can pinpoint the issue. Please keep it relevant to my issue.

Answer

Thank you @BenHarris for pointing me in the right direction. For all you future wanderers here is what you do:

If you are about where I am in your quest this is what you do:

add Jackson annotations to your pom.xml:

 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>{$jackson.version}</version>
</dependency>

Then in your web.xml:

 <servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>
      org.glassfish.jersey.servlet.ServletContainer
    </servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.your.project; com.fasterxml.jackson.jaxrs</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

So when you run Tomcat you're ObjectMapper will do its job for your request! Hope this helps others!

Comments