Http 415 Unsupported Media type error with JSON

JavaJsonHttp Status-Code-415

Java Problem Overview


I am calling a REST service with a JSON request and it responds with a HTTP 415 "Unsupported Media Type" error.

The request content type is set to ("Content-Type", "application/json; charset=utf8").

It works fine if I don't include a JSON object in the request. I am using the google-gson-2.2.4 library for JSON.

I tried using a couple of different libraries but it made no difference.

Can anybody please help me to resolve this?

Here is my code:

public static void main(String[] args) throws Exception
{

    JsonObject requestJson = new JsonObject();
    String url = "xxx";
    
    //method call for generating json

    requestJson = generateJSON();
    URL myurl = new URL(url);
    HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
    con.setDoOutput(true);
    con.setDoInput(true);
    
    con.setRequestProperty("Content-Type", "application/json; charset=utf8");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Method", "POST");
    OutputStream os = con.getOutputStream();
    os.write(requestJson.toString().getBytes("UTF-8"));
    os.close();

    
    StringBuilder sb = new StringBuilder();  
    int HttpResult =con.getResponseCode();
    if(HttpResult ==HttpURLConnection.HTTP_OK){
    BufferedReader br = new BufferedReader(new   InputStreamReader(con.getInputStream(),"utf-8"));  

        String line = null;
        while ((line = br.readLine()) != null) {  
        sb.append(line + "\n");  
        }
         br.close(); 
         System.out.println(""+sb.toString());  

    }else{
    	System.out.println(con.getResponseCode());
        System.out.println(con.getResponseMessage());  
    }  
     
}
public static JsonObject generateJSON () throws MalformedURLException

{
   String s = "http://www.example.com";
        s.replaceAll("/", "\\/");
	JsonObject reqparam=new JsonObject();
	reqparam.addProperty("type", "arl");
	reqparam.addProperty("action", "remove");
	reqparam.addProperty("domain", "staging");
	reqparam.addProperty("objects", s);
	return reqparam;

}
}

The value of requestJson.toString() is :

{"type":"arl","action":"remove","domain":"staging","objects":"http://www.example.com"}

Java Solutions


Solution 1 - Java

Not sure about the reason but Removing lines charset=utf8 from con.setRequestProperty("Content-Type", "application/json; charset=utf8") resolved the issue.

Solution 2 - Java

Add Content-Type: application/json and Accept: application/json

Solution 3 - Java

If you are making jquery ajax request, dont forget to add

contentType:'application/json'

Solution 4 - Java

This is because charset=utf8 should be without a space after application/json. That will work fine. Use it like application/json;charset=utf-8

Solution 5 - Java

If you are using AJAX jQuery Request this is a must to apply. If not it will throw you 415 Error.

dataType: "json",
contentType:'application/json'

Solution 6 - Java

If you get this in React RSAA middleware or similar, Add the headers:

  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(model),

Solution 7 - Java

HttpVerb needs its headers as a dictionary of key-value pairs

headers = {'Content-Type': 'application/json', 'charset': 'utf-8'}

Solution 8 - Java

Incase if you are giving a post request through Postman then make sure you have choosed these 2 options

1. JSON (application/json) should be choosed enter image description here

2. Content-Type - application/json

enter image description here

Solution 9 - Java

Add the HTTP header manager and add in it your API's header names and values. e.g. Content-type, Accept, etc. That will resolve your issue.

Solution 10 - Java

Some times Charset Metada breaks the json while sending in the request. Better, not use charset=utf8 in the request type.

Solution 11 - Java

I fixed this by updating the Request class that my Controller receives.

I removed the following class level annotation from my Request class on my server side. After that my client didn't get 415 error.

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement

Solution 12 - Java

I had the same issue with Postman. Adding Content-Type: application/json to the headers solved the issue.

Solution 13 - Java

I was sending "delete" rest request and it failed with 415. I saw what content-type my server uses to hit the api. In my case, It was "application/json" instead of "application/json; charset=utf8".

So ask from your api developer And in the meantime try sending request with content-type= "application/json" only.

Solution 14 - Java

I had the same issue. My problem was complicated object for serialization. One attribute of my object was Map<Object1, List<Object2>>. I changed this attribute like List<Object3> where Object3 contains Object1 and Object2 and everything works fine.

Solution 15 - Java

I know this is way too late to help the OP with his problem, but to all of us who is just encountering this problem, I had solved this issue by removing the constructor with parameters of my Class which was meant to hold the json data.

Solution 16 - Java

Add MappingJackson2HttpMessageConverter manually in configuration solved the problem for me :

@EnableWebMvc
@Configuration
@ComponentScan
public class RestConfiguration extends WebMvcConfigurerAdapter {

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
		messageConverters.add(new MappingJackson2HttpMessageConverter());
		super.configureMessageConverters(messageConverters);
	}
}

Solution 17 - Java

The reason can be not adding "annotation-driven" in your dispatcher servlet xml file. and also it may be due to not adding as application/json in the headers

Solution 18 - Java

> The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource. The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly. DOC

Solution 19 - Java

I have also faced this issue when working REST service with a JSON request and it responds with a HTTP 415 "Unsupported Media Type" error. These lines of codes will help you to resolve the issue.

> headers: { "Content-Type": "application/json", "accept": "/" },

After that, you should write code to encode the JSON body. For an example,

> body: jsonEncode({"username": username, "password": password})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3443794View Question on Stackoverflow
Solution 1 - Javauser3443794View Answer on Stackoverflow
Solution 2 - JavaParth SolankiView Answer on Stackoverflow
Solution 3 - JavakarthikView Answer on Stackoverflow
Solution 4 - JavaDhruvView Answer on Stackoverflow
Solution 5 - JavaDulacosteView Answer on Stackoverflow
Solution 6 - JavaNalan MadheswaranView Answer on Stackoverflow
Solution 7 - JavaMahmoud NasrView Answer on Stackoverflow
Solution 8 - Javaanand krishView Answer on Stackoverflow
Solution 9 - JavaArjun DuggalView Answer on Stackoverflow
Solution 10 - JavaMurali GundappanView Answer on Stackoverflow
Solution 11 - JavajavaPlease42View Answer on Stackoverflow
Solution 12 - JavaChamila MaddumageView Answer on Stackoverflow
Solution 13 - JavaRahul RastogiView Answer on Stackoverflow
Solution 14 - JavaspajdoView Answer on Stackoverflow
Solution 15 - JavaJero DungogView Answer on Stackoverflow
Solution 16 - JavaJéjéView Answer on Stackoverflow
Solution 17 - JavaBHARATHWAJView Answer on Stackoverflow
Solution 18 - JavaTiyebMView Answer on Stackoverflow
Solution 19 - Javatharaka_dil95View Answer on Stackoverflow