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"}
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"}
HTTP response status code 415 Unsupported Media Type is a client error that is returned by the server to indicate that the content of a message body is not supported.
Usage
When the 415 Unsupported Media Type error message is received, it may be as a result of the Content-Type or Content-Encoding headers being rejected by the server. Alternatively, the server may return this error based upon further inspection of the message body.
In the latter case, the server may indicate this error because it has trouble parsing or otherwise deciphering or recognizing the content. In cases where the server recognizes the media but it is not supported, the 415 Unsupported Media Type status is most accurate. However, if the content cannot be parsed and may contain an error then HTTP response 400 Bad Request or 422 Unprocessable Entity may be more appropriate.
This error is similar to 406 Not Acceptable, except that it is based on the Content-Type and Content-Encoding headers, rather than on the Accept header.
Note
Search engines like Google will not index a URL with 415 Unsupported Media Type response status, and consequently, URLs that have been indexed in the past but are now returning this HTTP status code will be removed from the search results.
Example
In the example, the client wants to send a message in plain text, but the server sends the 415 Unsupported Media Type error because it only accepts HTML messages. The client subsequently changes the Content-Type header but leaves the original message intact. The server can recognize that it is not a valid HTML structure and consequently, denies the request a second time.
Initial request
POST /blog/newmessage HTTP/1.1
Host: www.example.re
Content-Type: text/plain
Content-Length: 24
Good morning, Everybody!
Initial response, based on examining the Content-Type header
HTTP/1.1 415 Unsupported Media Type
Content-Type: text/html
Content-Length: 138
<html>
<head>
<title>Unsupported Format</title>
</head>
<body>
<p>Please use HTML to post new messages.</p>
</body>
</html>
Subsequent request to attempt to fool server
POST /blog/newmessage HTTP/1.1
Host: www.example.re
Content-Type: text/html
Content-Length: 24
Good morning, Everybody!
Subsequent response, based on examining the message body
HTTP/1.1 415 Unsupported Media Type
Content-Type: text/html
Content-Length: 174
<html>
<head>
<title>Unsupported Format</title>
</head>
<body>
<p>No HTML tags were found. Please ensure you use HTML to post new messages.</p>
</body>
</html>
Code references
.NET
HttpStatusCode.UnsupportedMediaType
Rust
http::StatusCode::UNSUPPORTED_MEDIA_TYPE
Rails
:unsupported_media_type
Go
http.StatusUnsupportedMediaType
Symfony
Response::HTTP_UNSUPPORTED_MEDIA_TYPE
Python3.5+
http.HTTPStatus.UNSUPPORTED_MEDIA_TYPE
Java
java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE
Apache HttpComponents Core
org.apache.hc.core5.http.HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE
Angular
@angular/common/http/HttpStatusCode.UnsupportedMediaType
Takeaway
The 415 Unsupported Media Type status code is a client error that occurs when the client sends, or attempts to send, a message body to the server that contains an unsupported media type. It may be denied based on the Content-Type or Content-Encoding headers, or after inspection of the message body.
See also
- RFC 7231
Last updated: August 2, 2023
While using images, video, and GIFs was not typical in the early days of the web, we now expect that a site offers appealing visuals as well as informative text. It’s also no surprise that when the communication between the browser and server goes awry due to a mismatch in media you’ll see an error. In this case, the “HTTP 415” error.
Because media is almost a prerequisite of the modern web, seeing an error relating to it means you’ll need a fix, fast. However, unlike other error fixes – especially for WordPress websites – this issue is one tough cookie. You may need some coding knowledge to solve this one, but this is something for later on.
For this post, we’re going to look into the “HTTP 415” error, and talk about what causes it. From there, we’ll discuss how you’d fix it.
Check Out Our Video Guide to Fixing the 415 Error
What the HTTP 415 Error Is
The “HTTP 415” error is one of many 4XX status codes. If you understand that it buddies up with errors such as a 404, you’ll begin to understand what’s happening.
In short, 4XX errors all deal with something missing that either the client or the server needs. The full name of the error – a “415 Unsupported Media Type” – gives the game away. The server is receiving a media file type that it doesn’t recognize or can’t accept.
Under most circumstances, you’ll see the “HTTP 415” error when you use an application programming interface (API). It’s a server-side issue, and next, we’ll discuss why this happens in the first place.
When the communication between the browser & server goes awry due to a mismatch in media, you’ll see an error. In this case, the “HTTP 415” error. 😅 Learn how to fix it here ✅Click to Tweet
Why the HTTP 415 Error Happens
Regardless of what you call it – the “HTTP 415” error, the “415 Unsupported Media Type” error – it means that the server refuses to accept a request from the browser. This will often be because whatever the browser sends (the payload) isn’t in the right format.
It’s a similar issue to the “422 Unprocessable Entity” error, as they both deal with the wrong data hitting the server, and the latter freaking out. It’s also worth pointing out that there is a distinction between the data the browser sends, and what the server receives. They may appear to be the same, but there’s a difference.
For example, a general error-catching strategy will stop a user from taking an unrecognized file type and uploading it through an interface that only accepts PNGs. However, if you don’t specify the exact types of media a server can process, it would trigger an error on the back end. On the front end, a user might not see anything at all. WordPress users get an admin screen notification:
The good news is that WordPress has a permissive infrastructure – think of the different file types you can upload to the Media Library, for example.
Even so, this is a developer-level issue rather than user error. As such, we’ll dive into what the fixes might be next.
How To Fix the HTTP 415 Error
To recap, the “HTTP 415” error tells you that the server won’t accept a file type because it doesn’t support that payload. This means there’s an issue within the underlying PHP code that needs a fix.
At this point, if you aren’t the developer of the site or theme, and you don’t have any coding skills, you’ll likely want to contact someone with expertise. Poking around in your theme’s files could cause an issue.
However, the Mozilla documentation on the error gives you two clues to begin your search – two ‘representation headers’: Content-Type, and Content-Encoding.
How the Content-Type and Content-Encoding Headers Work
The Content-Type header provides the client request with the resource before any encoding happens. It indicates the original media type of the resource. For example:
Content-Type: text/html; charset=UTF-8
Content-Type: image/jpeg;
In contrast, Content-Encoding is a list of all of the encodings the payload (i.e. your media) has, which is an indicator of how the file should be decoded in order to get the original payload.
Content-Encoding: gzip
Content-Encoding: br
As you can tell, file compression is a common way to encode data. This isn’t a problem in theory but will be if you don’t code this into the relevant files for your theme or plugin.
Finding a Fix For the HTTP 415 Error Code
Given the above, you’ll have three avenues to explore if you uncover an HTTP 415 error – all of them relating to your PHP code:
- You’ll want to ensure you send the right Content-Type header value.
- You will also want to make sure that the server can process whatever you specify for the Content-Type header.
- Check over what the server can process through the Accept header.
You won’t necessarily do this within core files, although you may do so as part of a REST API request. For example, a user from Stack Overflow had this exact issue when using pure PHP over cURL to make an API request.
There are two places to look. First, specify the correct file types within the Content-Type header:
$headers = array (
‘Content-Type’ => ‘application/json’,
…
Second, this user had a typo while declaring an invalid header key using the wp_remote_post() function:
$arg = array (
'header' => $headers,
…
Because “header” misses an “s”, it would throw the “HTTP 415” error. However, you’ll also want to make sure that the client can accept the right file types too. You’ll do this through another header: Accept. For example:
Accept: text/html
Accept: image/*
This makes sure both ends of the chain – the client and server side – can accept and send the right file types, and put a halt to the “HTTP 415” error for good.
Let’s look into the “HTTP 415” error- and talk about what causes it- in this guide 🚀Click to Tweet
Summary
Website errors are often straightforward to fix. We’ve done so a number of times on the Kinsta blog, and the nature of the platform means you can be ready to rock and roll in a short while. However, the “HTTP 415” is different, in that a fix is hard to come by if you’re not a developer.
The solution is to work with the Content-Type header values to make sure you send the right one to the server. You may also have a simple typo. This seems like a “doh” moment, but in this case, they can be tricky to spot, especially if your concern is with the content types you send to the server.
While the “HTTP 415” error is yours to fix, for other issues with your website, Kinsta is on call. We have our support team standing by to help you understand your site on the rare occasions it fails to load.
The 415 HTTP Status Code means that the request is unsupported media type indicates that the server rejects the request due to the payload format being unsupported. The format problem could be caused by the request’s specified Content-Type or Content-Encoding, or it could be the result of directly analyzing the data. The difference between HTTP Status Codes 400 and 415 is that the 400 HTTP Status Codes indicate that the server could not recognize the request due to invalid syntax, whereas the 415 HTTP Status Code indicates that the server does not support the required media format, and thus rejects the request.
What does 415 HTTP Status Code Mean?
The 415 HTTP Status Code is returned when the server rejects the requested resource due to the server’s inability to support the requested resource’s media format. The format issue could be caused by the request’s specified Content-Type or Content-Encoding, or by directly analyzing the contents.
How to Use 415 HTTP Status Code for a Website?
To use the 415 HTTP Status Code in a website, the web developer should send a form POST HTTP request (Content-Type: application/x-www-form-text) to the controller below, which returns an HTTP 415 Unsupported Media Type response.
How to Check 415 HTTP Status Code?
To check the 415 HTTP Status Code use the web browser network tab and developer tools for every resource that the client uses.
Which HTTP Method is used with 415 HTTP Status Code?
The HTTP methods that are used with the 415 HTTP Status Codes are given below.
- GET HTTP Method: The GET HTTP method is used in the 415 HTTP Response Status code. The GET method is used to get a representation of a resource. Requests made with the GET method should only return data.
- DELETE HTTP Method: The DELETE HTTP method is used in the 415 HTTP Response Status code. The DELETE method erases the specified resource from the system.
- POST HTTP Method: The POST HTTP method is used in the 415 HTTP Response Status code. The POST method submits an entity to the provided resource, frequently resulting in a change in the state of the server or other side effects.
The related HTTP Response Headers with 415 HTTP Status Code are listed below.
- Content-Type HTTP Header: The 415 HTTP Status Code is related with the Content-Type HTTP Header which is used to indicate the resource’s original media type (prior to any content encoding for transmission).
- Content-Encoding HTTP Header: The 415 HTTP Status Code is related with the Content-Encoding HTTP Header which is used to reduce the size of the media. When the server receives this information, it knows which encoding the user can use.
- Accept HTTP Header: The 415 HTTP Status Code is related to the Accept HTTP header which indicates the content types that the client is capable of understanding, as expressed in MIME types. The server selects one of the proposals via content negotiation and notifies the client via the Content-Type response header.
What are the Browsers Compatibility of 415 HTTP Status Code?
The 415 HTTP Status Code is compatible with all browsers including Chrome, Edge, Firefox, Internet Explorer, Opera, Safari, and Webview Android.
What are the other Similar Status Codes to 415 HTTP Status Code?
There are other similar HTTP Status Codes to the 415 HTTP Status Code. The following are listed below.
- 414 URI Too Long HTTP Status Code: The 414 HTTP Status Code is similar to the 415 HTTP Status Code because they are both client error responses. The 414 HTTP Status Code indicates that the client’s URI request is longer than the server will interpret.
- 416 Range Not Satisfiable HTTP Status Code: The 416 HTTP Status Code is similar to the 415 HTTP Status Code because they are both client error responses. The 416 HTTP Status Code indicates the range specified in the request’s Range header field cannot be accomplished. It is possible that the range is greater than the data size of the target URI.
- 417 Expectation Failed HTTP Status Code: The 417 HTTP Status Code is similar to the 415 HTTP Status Code because they are both client error responses. The 417 HTTP Status Code means the server is unable to fulfill the expectation specified in the Expect request header field.
- 418 I’m a teapot HTTP Status Code: The 418 HTTP Status Code is similar to the 415 HTTP Status Code because they are both client error responses. The 418 HTTP Status Code indicates that the server declines to use a teapot to brew coffee.
- Author
- Recent Posts
Holistic SEO & Digital has been built by Koray Tuğberk GÜBÜR. Holistic SEO is the process of developing integrated digital marketing projects with every aspect including Coding, Natural Language Processing, Data Science, Page Speed, Digital Analytics, Content Marketing, Technical SEO, and Branding. Structured, Semantic Search Engine improves its ability to detect the real-world entities, today. Having a simple website is not enough anymore. To show that your brand is authoritative, trustworthy, and expert on its own niche, you need entity-based Search Engine Optimization Projects. Holistic SEO & Digital’s main focus is on improving the brand’s organic visibility and growth potential.