我只想创建一个简单的 REST 服务,它使用 @GET
和 @POST
。
对于@GET
函数,一切正常,但对于@POST
,当我想在我的服务器上创建一个新用户时,浏览器只是保持饱和(不允许使用方法)。
我读了很多关于如何修复此错误的文章,但我还没有得到任何信息。
我的@POST
代码:
@Path("/hello")
public class HelloResource(){
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/post")
public Response createUser(@PathParam("name") String name,@PathParam("address") String address,@PathParam("birthYear") String birth,@PathParam("ps") String password) throws NotAllowedException,MethodNotFoundException,Exception {
DataStore.getInstance().putPerson(new Person(name, address, Integer.parseInt(birth), password));
String json = "{\n";
json += "\"status\": " + '"'+"CREATED" +'"'+ ",\n";
json+="}";
return Response.status(200).entity(json).build();
}}
我还尝试使用 (MediaType.APPLICATION.JSON) 和 (MediaType.TEXT_PLAIN) 添加 @Consumes
函数,但没有任何改变。
此外,我输入的用于发布的 URL 是:
http://localhost:8080/HelloREST/rest/hello/post?name=PouYad&address=mustbejsonlater&birthYear=2005&ps=12345
正如你所见,我也尝试了很多异常处理程序。
有人可以帮忙吗?
最佳答案
如果您在浏览器 URL 地址字段中输入您的 URL,它将不起作用,因为浏览器将发送“GET”请求。因此,您必须使用允许您发送“POST”的客户端,例如 PostMan。或者编写您自己的小型 httpConnection 函数来发送“POST”
您还必须将@PathParam更改为@FormParam才能使其工作(@QueryParam也可以工作,但因为它是POST,所以最好使用@FormParm)。
关于java - 尝试执行 POST 时不允许使用 REST Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61260811/