212

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

Tim
  • 5,435
  • 7
  • 42
  • 62
user3443794
  • 3,411
  • 3
  • 13
  • 9
  • Please update your question with the value of `requestJson.toString()` – Sabuj Hassan Mar 21 '14 at 18:22
  • 1
    Value of requestJson.toString is : {"type":"arl","action":"remove","domain":"staging","objects":"http://www.abc.com"} – user3443794 Mar 21 '14 at 18:30
  • Have you written the server part? If you do the same request with Postman (Chrome extensions, Google it), does it work? Perhaps the server does not accept the JSON content type for some reason? – joscarsson Mar 21 '14 at 19:18
  • Yes I tested that using soapUI. I sent the exact same request including json and got successful response from the server. – user3443794 Mar 21 '14 at 19:23
  • @joscarsson, since 14 Mar 2017, Postman chrome extension is deprecated. They moved to the native app. Here is their blog post: [http://blog.getpostman.com/2017/03/14/going-native/](http://blog.getpostman.com/2017/03/14/going-native/) – Serge Kishiko Jul 16 '18 at 10:11

25 Answers25

129

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

Gopal Singh Sirvi
  • 4,539
  • 5
  • 33
  • 55
user3443794
  • 3,411
  • 3
  • 13
  • 9
  • It's probably a bug in the ReST service. They're probably not expected the `charset` to be set in the Content-Type. My guess is that they're checking if the string `"application/json; charset=utf-8" == "application/json"`. That being said, JSON must be utf-8 so it's perfectly valid to leave out the charset. – Tim Martin Mar 28 '16 at 03:39
  • 37
    Because `charset=utf8` is not a valid character set designation. The correct version would be `charset=utf-8`. The dash is important. The list of valid character set designations is managed by IANA RFC2879: http://www.iana.org/assignments/character-sets/character-sets.xhtml – Berin Loritsch Jul 06 '17 at 17:33
  • 1
    Wasted a whole lot of time trying different things and then tried removing the charset=utf8 and it worked. Thanks. – Salman May 07 '18 at 10:42
  • In some implementations, like Dart http, `charset=UTF-8` is the only way to use it. – VoidMain Nov 08 '20 at 17:09
  • Which file contains this so I can remove it? – Etch Sep 29 '21 at 16:13
110

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

Parth Solanki
  • 3,268
  • 2
  • 22
  • 41
  • 8
    If you using **Postman** for testing, try to add this part to the **Headers**: Content-Type: application/json – Oliver Oct 04 '19 at 12:03
22

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

contentType:'application/json'
karthik
  • 7,041
  • 1
  • 13
  • 12
16

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

Matthew Read
  • 1,365
  • 1
  • 30
  • 50
Dhruv
  • 185
  • 1
  • 2
  • 2
    This is incorrect; spaces are allowed and should be ignored; see https://tools.ietf.org/html/rfc2046 . – djb Jan 03 '18 at 15:20
12

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

headers = {'Content-Type': 'application/json', 'charset': 'utf-8'}
Mahmoud Nasr
  • 564
  • 7
  • 11
8

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

  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(model),
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
7

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'
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
7

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

anand krish
  • 4,281
  • 4
  • 44
  • 47
2

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.

2

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

Chamila Maddumage
  • 3,304
  • 2
  • 32
  • 43
2

I was facing the same issue and the solution was to remove

'mode': 'no-cors'

and adding the hostname as an allowed origin at backend server. Setting mode to 'no-cors' will always take "Content-Type" as "text/plain". For more info, visit info

Jyoti Duhan
  • 988
  • 1
  • 16
  • 26
1

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

  • 2
    utf8 just isn't a valid character set. Look at the spec: http://www.iana.org/assignments/character-sets/character-sets.xhtml – Berin Loritsch Jul 06 '17 at 17:34
1

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
javaPlease42
  • 4,699
  • 7
  • 36
  • 65
1

In my case: on the body params I set the param to text type instead of JSON I thought its all the same .:)

Khalid
  • 343
  • 3
  • 16
0

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.

Rahul Rastogi
  • 4,486
  • 5
  • 32
  • 51
0

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.

spajdo
  • 901
  • 9
  • 20
0

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.

Jero Dungog
  • 379
  • 1
  • 10
0

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);
    }
}
Jéjé
  • 115
  • 2
  • 11
0

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

BHARATHWAJ
  • 39
  • 1
  • 10
0

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

Community
  • 1
  • 1
TiyebM
  • 2,684
  • 3
  • 40
  • 66
0

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

tharakadil95
  • 13
  • 1
  • 6
0

In the Postman, in the Headers, you might insert the folows Keys and values Key = Content_Type VALUE application/json Key = Accept VALUE application/json

It is must work!!!

0

I was having same issue even after adding correct “Content-Type” & “content-type” headers. The issue resolved when I added “x-version” header with value as “4”.

Sagar
  • 13
  • 6
0

Adding 'Content-Type': '*/*' and 'accept': '*/*' in headers resolve this problem for me.

elouassif
  • 308
  • 1
  • 10
0

Your request might need a empty body {} even if you have no body data.

body: {}
Satbir Kira
  • 792
  • 6
  • 21