简体   繁体   中英

Jersey Method not allowed 405

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 MessageBodyReader s 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) {}

First be sure that the path is /log/log/logevent

Then try changing the request/reponse type:

You should use application/json;charset=UTF-8 (W3C XHR spec), moreover your webservice doesn't respond with JSON but ouptut a boolean, maybe you should change the response type.

For example with UTF-8:

JAX-RS

@Consumes("application/json;charset=UTF-8")

jQuery

contentType:"application/json;charset=UTF-8"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM