user3443794
user3443794

Reputation: 3721

Http 415 Unsupported Media type error with JSON

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

Upvotes: 239

Views: 1098801

Answers (27)

Mahmoud Nasr
Mahmoud Nasr

Reputation: 642

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

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

Upvotes: 14

kwick
kwick

Reputation: 787

You can re-check the target URL as well carefully, as in my case when I was facing this issue there was a slight change in the URL I was passing mistakenly. Fixing the URL simply fixed this issue for me.

Upvotes: 0

Vusal
Vusal

Reputation: 1

General Request URL: http://localhost:8080/education/students Request Method: POST Status Code: 415 Remote Address: [::1]:8080 Referrer Policy: strict-origin-when-cross-origin

Response Headres Accept: application/json, application/*+json Connection: keep-alive Content-Type: application/json Date: Wed, 15 May 2024 18:30:40 GMT Keep-Alive: timeout=60

Request Headers Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US;q=0.8,en;q=0.7 Connection: keep-alive Content-Length: 109 Content-Type: text/plain;charset=UTF-8 Transfer-Encoding: chunked

I had the same problem, everything is fine, only I got 415-unsupported-media-type-error because I didn't say that I wanted to send application/json. In Request Headers, I say that I sent Content-Type: text/plain;charset=UTF-8, but I said Request Headers I should tell you that I want to send you application/json, application/*+json

Upvotes: 0

user3443794
user3443794

Reputation: 3721

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

Upvotes: 133

S s
S s

Reputation: 877

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

body: {}

Upvotes: 0

elouassif
elouassif

Reputation: 318

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

Upvotes: 0

Sagar
Sagar

Reputation: 13

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”.

Upvotes: 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!!!

Upvotes: 0

Khalid
Khalid

Reputation: 371

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

Upvotes: 1

Jyoti Duhan
Jyoti Duhan

Reputation: 1094

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

Upvotes: 3

anand krish
anand krish

Reputation: 4415

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

Upvotes: 9

Chamila Maddumage
Chamila Maddumage

Reputation: 3866

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

Upvotes: 2

tharakadil95
tharakadil95

Reputation: 13

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

Upvotes: 0

Parth Solanki
Parth Solanki

Reputation: 3448

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

Upvotes: 124

user3408531
user3408531

Reputation:

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

Upvotes: 0

javaPlease42
javaPlease42

Reputation: 4963

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

Upvotes: 1

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10562

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

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

Upvotes: 8

BHARATHWAJ
BHARATHWAJ

Reputation: 39

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

Upvotes: 0

Jéjé
Jéjé

Reputation: 115

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

Upvotes: 0

Du-Lacoste
Du-Lacoste

Reputation: 12757

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'

Upvotes: 7

Arjun Duggal
Arjun Duggal

Reputation: 31

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.

Upvotes: 2

Jero Dungog
Jero Dungog

Reputation: 379

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.

Upvotes: 0

Murali Gundappan
Murali Gundappan

Reputation: 13

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

Upvotes: 1

spajdo
spajdo

Reputation: 953

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.

Upvotes: 0

Dhruv
Dhruv

Reputation: 183

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

Upvotes: 15

karthik
karthik

Reputation: 7529

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

contentType:'application/json'

Upvotes: 23

Rahul Rastogi
Rahul Rastogi

Reputation: 4698

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.

Upvotes: 0

Related Questions