Jersey Method not allowed 405

冷暖自知 提交于 2019-12-23 20:01:06

问题


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.


回答1:


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



回答2:


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"


来源:https://stackoverflow.com/questions/18147772/jersey-method-not-allowed-405

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!