[英]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.我正在使用 JSON 请求调用 REST 服务,它响应
HTTP 415 "Unsupported Media Type"
错误。
The request content type is set to ("Content-Type", "application/json; charset=utf8")
.请求内容类型设置为
("Content-Type", "application/json; charset=utf8")
。
It works fine if I don't include a JSON object in the request.如果我不在请求中包含 JSON 对象,它工作正常。 I am using the
google-gson-2.2.4
library for JSON.我将
google-gson-2.2.4
库用于 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 : requestJson.toString()
的值是:
{"type":"arl","action":"remove","domain":"staging","objects":"http://www.example.com"}
不确定原因,但从con.setRequestProperty("Content-Type", "application/json; charset=utf8")
删除行charset=utf8
解决了该问题。
添加Content-Type
: application/json
和Accept
: application/json
如果您正在制作 jquery ajax 请求,请不要忘记添加
contentType:'application/json'
This is because charset=utf8
should be without a space after application/json
.这是因为
charset=utf8
在application/json
之后应该没有空格。 That will work fine.那会工作得很好。 Use it like
application/json;charset=utf-8
像
application/json;charset=utf-8
一样使用它
If you are using AJAX
jQuery
Request this is a must to apply.如果您使用
AJAX
jQuery
请求,这是必须应用的。 If not it will throw you 415
Error.如果不是,它会抛出
415
错误。
dataType: "json",
contentType:'application/json'
If you get this in React RSAA middleware or similar, Add the headers:如果您在 React RSAA 中间件或类似软件中获得此信息,请添加标头:
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(model),
HttpVerb 需要将其标头作为键值对字典
headers = {'Content-Type': 'application/json', 'charset': 'utf-8'}
Add the HTTP header manager and add in it your API's header names and values.添加 HTTP 标头管理器并将您的 API 的标头名称和值添加到其中。 eg Content-type, Accept, etc. That will resolve your issue.
例如内容类型、接受等。这将解决您的问题。
Some times Charset Metada breaks the json while sending in the request.有时,Charset Metada 在发送请求时会破坏 json。 Better, not use charset=utf8 in the request type.
最好不要在请求类型中使用 charset=utf8 。
I fixed this by updating the Request
class that my Controller receives.我通过更新我的控制器接收的
Request
类来解决这个问题。
I removed the following class level annotation from my Request
class on my server side.我从服务器端的
Request
类中删除了以下类级别的注释。 After that my client didn't get 415 error.在那之后,我的客户没有收到 415 错误。
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
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.
415(不支持的媒体类型)状态代码表示源服务器拒绝为请求提供服务,因为目标资源上的有效负载采用此方法不支持的格式。 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.
格式问题可能是由于请求指示的 Content-Type 或 Content-Encoding,或者是直接检查数据的结果。 DOC
文件
I was sending "delete" rest request and it failed with 415. I saw what content-type my server uses to hit the api.我正在发送“删除”rest 请求,但它以 415 失败。我看到了我的服务器用来访问 api 的内容类型。 In my case, It was "application/json" instead of "application/json; charset=utf8".
就我而言,它是“application/json”而不是“application/json; charset=utf8”。
So ask from your api developer And in the meantime try sending request with content-type= "application/json" only.因此,请询问您的 api 开发人员,同时尝试仅使用 content-type="application/json" 发送请求。
I had the same issue.我遇到过同样的问题。 My problem was complicated object for serialization.
我的问题是序列化的复杂对象。 One attribute of my object was
Map<Object1, List<Object2>>
.我的对象的一个属性是
Map<Object1, List<Object2>>
。 I changed this attribute like List<Object3>
where Object3
contains Object1
and Object2
and everything works fine.我改变了这个属性,比如
List<Object3>
其中Object3
包含Object1
和Object2
并且一切正常。
我知道这对于帮助 OP 解决他的问题为时已晚,但对于我们所有刚刚遇到此问题的人来说,我已经通过删除带有我的类的参数的构造函数来解决这个问题,该参数用于保存 json 数据。
Add MappingJackson2HttpMessageConverter manually in configuration solved the problem for me :在配置中手动添加 MappingJackson2HttpMessageConverter 为我解决了这个问题:
@EnableWebMvc
@Configuration
@ComponentScan
public class RestConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(new MappingJackson2HttpMessageConverter());
super.configureMessageConverters(messageConverters);
}
}
The reason can be not adding "annotation-driven" in your dispatcher servlet xml file.原因可能是没有在您的调度程序 servlet xml 文件中添加“注释驱动”。 and also it may be due to not adding as application/json in the headers
也可能是因为没有在标头中添加为 application/json
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.在使用 JSON 请求处理 REST 服务时,我也遇到了这个问题,它以 HTTP 415“不支持的媒体类型”错误响应。 These lines of codes will help you to resolve the issue.
这些代码行将帮助您解决问题。
headers: { "Content-Type": "application/json", "accept": " / " },
headers: { "Content-Type": "application/json", "accept": " / " },
After that, you should write code to encode the JSON body.之后,您应该编写代码来对 JSON 正文进行编码。 For an example,
例如,
body: jsonEncode({"username": username, "password": password})
正文:jsonEncode({“用户名”:用户名,“密码”:密码})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.