我正在使用 Jersey Framework(JAX-RS 实现)来构建 RESTful Web 服务。
我无法使用 @DELETE REST 方法,因为当我尝试调用它时它会抛出异常。以下 @DELETE 方法用于删除员工:
@Path("/employees")
public class EmpResource {
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteEmployee(JAXBElement<String> r) throws ClassNotFoundException, SQLException {
String name = r.getValue();
String response = DAOaccess.deleteEmp(name);
return Response.noContent().build();
}
我使用以下代码块来调用该服务:
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RestApp/sample/employees");
String input = "{\"name\":\"John\"}";
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class,input);
当我运行客户端时,它抛出以下异常:
Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method DELETE doesn't support output
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.delete(WebResource.java:599)
如果有人能指导我如何解决这个问题,那就太好了?
最佳答案
这是 HTTPUrlConnection 类实现中的 java 错误:
http://bugs.sun.com/view_bug.do?bug_id=7157360
应该在java 8中解决......
同时,实际上,要将 json 发送到 REST 服务,您必须像 @Micer 所说的那样发送路径参数,或者创建您自己的 HttpUrlConnection,将请求方法设置为 POST 并使用“X-HTTP_method-”覆盖它Override”表示您希望 DELETE 执行如下操作:
public static void remove(String dflowname) throws IOException, ParseException {
String jsonResponse = "";
URL url = new URL(deleteuri);
HttpURLConnection connection = null;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// We have to override the post method so we can send data
connection.setRequestProperty("X-HTTP-Method-Override", "DELETE");
connection.setDoOutput(true);
// Send request
OutputStreamWriter wr = new OutputStreamWriter(
connection.getOutputStream());
wr.write(dflowname);
wr.flush();
// Get Response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
jsonResponse = jsonResponse.concat(line);
}
wr.close();
rd.close();
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(jsonResponse);
System.out.println(obj.get("status").toString());
}
来源:https://groups.google.com/a/openflowhub.org/forum/#!msg/floodlight-dev/imm_8drWOwU/Uu4h_u3H6HcJ
关于java - 无法在 REST/JERSEY 中调用 @DELETE Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670169/