我使用澤西我的休息服務器和當我嘗試轉發POST請求到相對GET資源時,我得到一個HTTP 405錯誤。澤西PathParam與HTTP 405錯誤
@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;
}
}
捲曲-X POST -d { 「方法」: 「mytest的」, 「PARAMS」:{ 「名稱」: 「插口」}}本地主機/ anythingbutmytest
捲曲-X GET本地主機/ mytest?name = jack
上面這兩個curl工作正常。但我得到一個405錯誤,當我嘗試請求這樣的:
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)
......
我該怎麼辦?
-------------------------------------更新-------- -----------------------------
curl -X POST -d {「method」:「mytest」,「params 「:{」name「:」jack「}} localhost/mytest
此捲曲工作正常,當我添加一個像下面的post方法。 但是我會爲每個GET方法寫一個相同的POST方法,有沒有其他解決方案?
@POST @Path("/mytest") @Produces(MediaType.APPLICATION_JSON) public String postMyTest(@Context UriInfo uriInfo, String body) throws Exception { return postRequest(uriInfo.getPath(), uriInfo, body); }
除此之外,還有沒有其他的方式來重新路由POST請求到同一類中的方法沒有建立一個新的HTTP請求?
我認爲這是設計(規範)。您可能只需要創建一個額外的@POST @Path(「/ mytest」)方法來處理針對該特定路由的POST。 –
謝謝,當我添加@POST @Path(「/ mytest」)方法時它工作正常。但它似乎有點多餘,請參閱我的更新。 – jackiefang