I'm trying to send an JSON object to my Java EE server using Ajax and JAX RS.
When i do the client request i get the HTTP415 error.
Here's the code..
var obj = {nome:"a", cognome:"b"};
$.post("http://localhost:8080/MyApp/resources/Class/Method",obj).done(function(data) {
alert( "..." + data);
})
.fail(function() {
alert( "error" );
});
Java Class:
public class Oggetto implements Serializable{
private static final long serialVersionUID = 1L;
private String nome;
private String cognome;
public Oggetto() {}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
} }
And the Rest Class:
@POST
@Path("/Method")
@Consumes(MediaType.APPLICATION_JSON)
public String Mex(final Oggetto obj) {
return "ok";
}
I get an error from the Browser console. HTTP415: UNSUPPORTED MEDIA TYPE
I tried with an AngularJS call, but it's the same.
What am I doing wrong?
Thanks.
You are not setting the content type. Also you need to stringify
the request object. See this example with $.ajax
( $post
is a shorthand)
$.ajax({
type: "POST",
url: "http://localhost:8080/MyApp/resources/Class/Method",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8"
}
}).done(function(data){
As your Rest class method annotated with @Consumes(MediaType.APPLICATION_JSON) so it only expects Content-Type of the request to be application/json.
Either remove @Consumes(MediaType.APPLICATION_JSON) or send Content-Type with request as shown above by pedrofb .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.