I'm using jersey for my rest server, and I got a HTTP 405 error, when I try to forward POST request to relative GET resource.
@Path("/")
public class MyResource {
@POST
@Path("/{method}")
@Produces(MediaType.APPLICATION_JSON)
public String postRequest(@PathParam("method") String method, @Context UriInfo uriInfo, String body) throws IOException {
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(body).getAsJsonObject();
JsonObject params = root;
if (root.has("method")) {
method = root.get("method").getAsString();
params = root.getAsJsonObject("params");
}
UriBuilder forwardUri = uriInfo.getBaseUriBuilder().path(method);
for (Map.Entry<String, JsonElement> kv : params.entrySet()) {
forwardUri.queryParam(kv.getKey(), kv.getValue().getAsString());
}
return new SimpleHttpClient().get(forwardUri.toString());
}
@GET
@Path("/mytest")
@Produces(MediaType.APPLICATION_JSON)
public String getTest(@QueryParam("name") String name) {
return name;
}
}
curl -X POST -d {"method":"mytest","params":{"name":"jack"}} localhost/anythingbutmytest
curl -X GET localhost/mytest?name=jack
These two curl above work fine. But I get a 405 error , when I try to request like this:
curl -X POST -d {"method":"mytest","params":{"name":"jack"}} localhost/mytest
javax.ws.rs.NotAllowedException: HTTP 405 Method Not Allowed
at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.getMethodRouter(MethodSelectingRouter.java:466)
at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.access$000(MethodSelectingRouter.java:94)
......
What should I do?
-------------------------------------Update-------------------------------------
curl -X POST -d {"method":"mytest","params":{"name":"jack"}} localhost/mytest
This curl work fine, when I add a post method like below. But I will write a same POST method for every GET Method like that, is there any other solution?
@POST @Path("/mytest") @Produces(MediaType.APPLICATION_JSON) public String postMyTest(@Context UriInfo uriInfo, String body) throws Exception { return postRequest(uriInfo.getPath(), uriInfo, body); }
Besides, is there any other way to re-route POST request to a method in the same class without building a new HTTP request?
You should make
@POST
@Path("/mytest")
and not "getTest" method.Reason is below.
Command
curl -X POST -d {"method":"mytest","params":{"name":"jack"}} localhost/anythingbutmytest
will accept because of
@Path("/{method}") .
But
curl -X POST -d {"method":"mytest","params":{"name":"jack"}} localhost/mytest
will not accept because of
@GET
@Path("/mytest")
POST does not match GET.
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.