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
Ошибка 415 обладает следующей спецификацией и обозначением: RFC7231, секция 6.5.13: HTTP 415 Unsupported Media Type и Hypertext Transfer Protocol/1.1: Semantics and Content.
Несколько слов о теории ошибок
Коды ошибок HTTP клиента указывают пользователю на то, что не удается получить необходимый ресурс, по вине пользователя либо клиента. Оповещение об этом состоит из двух частей. В первой части содержится целое трёхзначное число. Первая цифра обозначает классификацию состояния (на данный момент выделяются пять классов). Следом за трехзначным числом на английском языке прописывается разъяснительная фраза, уточняющая причину. В данном случае это выглядит так: «4**: Client Error».
Фундаментально протокол HTTP моделируется путем взаимодействий клиента и сервера, при этом разделяются обязанности приложений на серверные и клиентские, данный протокол достаточно строго следует созданной модели, в которой определяются особые коды ошибок. Одни возникают по вине серверных приложений, другие по вине человека либо приложения клиента, которое использует человек.
Возникновение проблемы, отвечающей на запрос, HTTP 415 Unsupported Media Type обозначает, что сервер не может выполнить запрашиваемое действие, так как данный формат файла он не поддерживает.
Проще говоря в запросе обнаружилась часть, выполненная в неподдерживаемом формате. В самом запросе не отображается типы медиа файлов, поддерживаемые ресурсом либо сервером. К примеру, пользователь пытается открыть изображение, формат которого не поддерживает сервер либо нет возможности его обработать. Иначе говоря, содержимое не поддерживает Multipurpose Internet Mail Extension тип.
Ошибка 415, обозначающая проблему с форматом, может случиться при открывании Content-Type либо Content-Encoding. Она обладает следующей спецификацией и обозначением: RFC7231, секция 6.5.13: HTTP 415 Unsupported Media Type и Hypertext Transfer Protocol/1.1: Semantics and Content. Связано это, в большей степени, с проблемами в медиа файлах, которые не желает воспринимать сервер по каким-либо причинам.Также это может возникнуть в результате прямого контроля данных.
Проблема ошибки 415 зависит от администратора сервера или сайт. От пользователя ничего не зависит в решении этого вопроса.
В результате частого возникновения проблемы, у многих пользователей возникает вопрос: «как исправить ошибку 415?».
Самые простые способы решения проблемы:
Рассмотрим легкие варианты того, как исправить ошибку 415, чтобы на запрос не возникал ответ HTTP 415 Unsupported Media Type:
- Можно скопировать проблемный файл в другую папку, а затем переместить обратно на прежнее место и он станет открываться без проблем (не всегда).
- Изменение формата файла, также может принести положительный результат. Переформатирование возможно произвести при помощи специальных программ.
- Возможны неполадки с mime типами в apache. MIME — многоцелевые расширения электронной почты. Назначение их заключается в передаче файлов, по сетевой паутине, следующих типов: изображения; музыка; тексты; видео; архивы и т.п. Направление MIME-типа применяется в HTML, в основном, в момент передачи информационных данных и добавляет их на страницу разных объектов. Можно попробовать переименовать файл, желательно чтобы имя было попроще. Это должно исправить положение.
- В случае, когда запрос серверу выглядит таким образом:
$.post(‘/ajax/load’, {act: act}, function(d){
//….
});
Можно поменять $.post на $.get и все станет нормально открываться.
- Если, все же, по каким-либо причинам сервер не желает обрабатывать указанный тип данных, то лучше обратиться к специалисту.
- Сущность кодирования объема информации применяется, чтобы сжать тип носителя. При существовании такового, его функция обозначает, какие кодировки применялись к основе заголовка. Что дает возможность пользователю узнать процесс декодирования, и таким образом стать обладателем медиа-типом, от которого зависит его передача. Многие советуют по максимуму сжать данные и, далее, использовать освобожденное пространство, но надо помнить, что существуют такие типы ресурсов, как изображения формата jpeg и многие аналогичные, которые уже находятся в сжатом состоянии. Зачастую дополнительное сжатие не способствует уменьшению размера загруженного места, а наоборот увеличивает его, что приводит к непредсказуемым последствиям.
- Заголовок Content применяется, чтобы опознать вид MIME ресурса. В ответных отзывах сервера этот заголовок оповещает клиента, каким будет вид подаваемого контента. Часто бывает, что браузеры делают попытки самостоятельно опознать MIME вид подающего контента, однако такие действия могут быть непредсказуемые. Предотвратить подобные ситуации можно, установив в строке X-Content-Type-Options обозначение nosniff.
Проблема на сайте
Когда, после подключения подсказок, выдается ошибка 415, получив наподобие следующей информативной строки: «family»: «CLIENT_ERROR», «reason»…, эта причина, вероятно, возникла в отстойнике WebAsyst, сопряженная со страницей интернета. Программа wa.core.js на поле с тремя тройками содержит мощный перехват информации ajaxSend, где переписывается Content-Type другой строкой.
Такая пользовательская функция перехватывает поступление Content-Type для любой операции AJAX, запрашиваемой со страницы пользователя. А также она затирает Content-Type = application/json на ошибочное значение. Можно установить расширение возможностей, однако всеобъемлющий перехватчик информации, который описывался выше, может перенаправить его не в то направление.
Избавиться от неисправности возможно, запретив замену запросов на подсказки.
Рекомендации
Не стоит наугад пытаться исправить неполадку, которая появляется при открытии медиа файлов либо при подключенных подсказках. Самостоятельное вмешательство может создать еще больше проблем, особенно когда отсутствует опыт в подобных делах.
Желательно, при возникновении трудностей, обращаться за помощью к опытным программистам либо взять у них устный совет.
Не нужно следовать советам предоставленным на ненадежных сайтах, так как некоторые страницы содержат не достоверную информацию.
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.
BNAME.RU » Код ошибки HTTP 415 Unsupported Media Type
Что означает ошибка 415 Unsupported Media Type?
Сообщение 415 об ошибке указывает, что API не может обработать тип носителя, предоставленный клиентом, как указано в заголовке запроса типа контента. Например, запрос клиента содержит данные в формате application/xml, а API готов только для обработки application/json. В этом случае клиент получит ответ 415. Например, клиент загружает изображение как image/svg + xml, но сервер требует, чтобы изображения использовали другой формат.
Ошибка 415 — Unsupported Media Type (Неподдерживаемый тип медиа) — возникает в веб-разработке, когда сервер не может обработать запрос, так как тип содержимого, указанный клиентом в заголовке Content-Type, не поддерживается сервером или не совпадает с ожидаемым типом.
Понимание ошибки 415
Ошибка 415 может возникать при использовании пути ‘server/files/save’ в фреймворке Атернос. Этот путь используется для сохранения файлов на сервере, но при передаче файла происходит ошибка 415, что может указывать на проблему с типом содержимого файла.
Когда клиент отправляет файл на сервер, он должен указать тип содержимого (например, image/jpeg для изображений или application/pdf для PDF-файлов) в заголовке Content-Type. Если сервер не может распознать или обработать этот тип содержимого, будет сгенерирована ошибка 415.
Решение проблемы
Чтобы устранить ошибку 415 при использовании пути ‘server/files/save’ в Атерносе, следуйте этим рекомендациям:
-
Проверьте тип содержимого файла: убедитесь, что тип содержимого, указанный в заголовке Content-Type, соответствует типу файла, который вы пытаетесь сохранить на сервере.
-
Убедитесь, что сервер поддерживает указанный тип файла: проверьте, что сервер настроен на обработку и сохранение файлов с этим типом содержимого. Некоторые серверы могут требовать дополнительной конфигурации для поддержки различных типов файлов.
-
Используйте правильное значение Content-Type: убедитесь, что в заголовке Content-Type указан правильный тип файла. Например, для изображений используйте image/jpeg, image/png и т.д., а для документов — application/pdf, application/msword и другие соответствующие типы.
-
Проверьте кодировку файла: если проблема не связана с типом содержимого, убедитесь, что файл правильно закодирован. Ошибки в кодировке могут привести к возникновению ошибок 415.
-
Обратитесь к документации: изучите документацию фреймворка Атернос или сервера, которыми вы пользуетесь, чтобы узнать подробности о поддерживаемых типах файлов и настройках сервера, которые могут помочь в устранении ошибки 415.
Заключение
Ошибка 415 при использовании пути ‘server/files/save’ в Атерносе может быть вызвана неправильным типом содержимого файла, его недоступностью на сервере или ошибкой в кодировке файла. Следуя рекомендациям из этого руководства, вы сможете устранить ошибку 415 и успешно сохранить файл на сервере в фреймворке Атернос.