Java 不允许泽西方法 405

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18147772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:46:37  来源:igfitidea点击:

Jersey Method not allowed 405

javaweb-servicesrestjerseyjax-rs

提问by Ritesh

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:

我是其他服务的新手。我正在尝试创建一个接受来自客户端的 json 字符串的服务。使用 JQuery 调用此服务时出现 405 错误。下面是 ws 的 Java 代码:

@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:

用于发布 JSON 的 jQuery 代码是:

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/getdataI get the response.

出了什么问题?该帖子不起作用,但是当我使用 URL 点击 get 时,http://<serverip>/log/log/getdata我得到了响应。

采纳答案by Michal Gajdos

JSON MessageBodyReaders are able to unmarshal JSON stream into a JAXB bean (or POJO) but not into a String. Create a JAXB bean like:

JSONMessageBodyReader能够将 JSON 流解组为 JAXB bean(或 POJO),但不能解组为 String。创建一个 JAXB bean,如:

@XmlRootElement
public class User {

    private String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(final String userName) {
        this.userName = userName;
    }
}

and change your POSTresource method to:

并将您的POST资源方法更改为:

@POST
@Path("logevent")
@Consumes(MediaType.APPLICATION_JSON)
public boolean logEvent(User obj) {}

回答by mguimard

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

首先确定路径是 /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.

您应该使用application/json;charset=UTF-8(W3C XHR 规范),而且您的网络服务不响应 JSON 而是输出一个布尔值,也许您应该更改响应类型。

For example with UTF-8:

例如使用 UTF-8:

JAX-RS

JAX-RS

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

jQuery

jQuery

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