I am new to the rest services. I am trying to create a service that accepts json string from a client. I am getting 405 error when I am calling this service using JQuery. Below is the Java code for ws:
@POST
@Path("logevent")
@Consumes(MediaType.APPLICATION_JSON)
public boolean logEvent(String obj)
{
System.out.println(obj);
return true;
}
and
@Path("getdata")
@GET
public String getData()
{
return "Hello";
}
and jQuery code for posting the JSON is:
var json ="{\"userName\":\"testtest\"}";
var json_data = JSON.stringify(json);
$.ajax({
type: "POST",
url: "http://localhost:8080/log/log/logevent",
// The key needs to match your method's input parameter (case-sensitive).
data: json_data,
contentType: "application/json",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
What is going wrong? The post is not working, however when I hit the get using the URL http://<serverip>/log/log/getdata I get the response.
JSON MessageBodyReaders are able to unmarshal JSON stream into a JAXB bean (or POJO) but not into a String. Create a JAXB bean like:
@XmlRootElement
public class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(final String userName) {
this.userName = userName;
}
}
and change your POST resource method to:
@POST
@Path("logevent")
@Consumes(MediaType.APPLICATION_JSON)
public boolean logEvent(User obj) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With