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"}
Ошибка 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 на ошибочное значение. Можно установить расширение возможностей, однако всеобъемлющий перехватчик информации, который описывался выше, может перенаправить его не в то направление.
Избавиться от неисправности возможно, запретив замену запросов на подсказки.
Рекомендации
Не стоит наугад пытаться исправить неполадку, которая появляется при открытии медиа файлов либо при подключенных подсказках. Самостоятельное вмешательство может создать еще больше проблем, особенно когда отсутствует опыт в подобных делах.
Желательно, при возникновении трудностей, обращаться за помощью к опытным программистам либо взять у них устный совет.
Не нужно следовать советам предоставленным на ненадежных сайтах, так как некоторые страницы содержат не достоверную информацию.
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
If you’re a developer who has worked with web APIs, you might have come across the HTTP 415 “Unsupported Media Type” error. This error occurs when the server doesn’t support the media type that’s being used in the request. In this tutorial, we’ll discuss one common cause of the HTTP 415 error and how to fix it.
Introduction
The HTTP 415 “Unsupported Media Type” error occurs when the server doesn’t support the media type in the request. This error can be frustrating to deal with, especially when it’s not immediately clear what’s causing it. In this article, we’ll discuss one common cause of the HTTP 415 error and how to fix it by adding Content-Type: application/json
to your requests.
The Problem
The HTTP 415 error typically occurs when a client sends a request to a server using a media type that the server doesn’t support. For example, if a server expects JSON data but receives XML data instead, it will return the HTTP 415 error. This error can also occur if the client fails to specify a media type in the request headers.
The Solution
To fix the HTTP 415 error, you need to make sure that your request includes the correct media type in the Content-Type
header. In most cases, when you’re sending JSON data, the media type should be application/json
.
Here’s an example of faulty code that could result in an HTTP 415 error:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MyHttpClient { public String sendPostRequest(String endpoint, String requestBody) throws IOException { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/plain"); // Other request headers go here conn.getOutputStream().write(requestBody.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } }
In this example, the sendPostRequest
method sends a POST request to an API endpoint. However, it sets the Content-Type
header to text/plain
, which is not the correct media type for JSON data. If you try to send JSON data using this method, you’ll likely receive an HTTP 415 error.
To fix this, you need to update the Content-Type
header to application/json
. Here’s the updated code:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MyHttpClient { public String sendPostRequest(String endpoint, String requestBody) throws IOException { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); // Other request headers go here conn.getOutputStream().write(requestBody.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } }
By updating the Content-Type
header to application/json
, this code should now be able to send JSON data without triggering the HTTP 415 error.
Conclusion
The HTTP 415 error can be a frustrating issue to deal with, but fortunately, it’s often easy to fix.