现在我有一个名为Users.java的Restful Web服务,假冒将用户添加到假数据库
@Path("/users")
public class UsersService {
@POST
public Response handlePost(String requestBody) {
addUserToDatabase(requestBody);
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("status", "success");
jsonMap.put("resource-uri", "/users/12"); // assume 12 is the ID of the user we pretended to create
Gson gson = new Gson();
return Response.status(200).entity(gson.toJson(jsonMap)).build();
}
private boolean addUserToDatabase(String requestBody) {
Gson gson = new Gson();
Map<String, String> user = gson.fromJson(requestBody, new TypeToken<Map<String, String>>() {
}.getType());
for (String key : user.keySet()) {
System.out.println(key + ": " + user.get(key));
}
return true; // lie and say we added the user to the database
}
}
在这里使用Post请求调用它,这些是示例
public HttpResponse postRequest(String relativePath, Map<String, String> map){
try {
String fullPath = buildURL(relativePath);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost getRequest = new HttpPost(fullPath);
Gson gson = new Gson();
String postEntity = gson.toJson(map);
getRequest.setEntity(new StringEntity(postEntity));
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
httpClient.getConnectionManager().shutdown();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// POST
Map<String, String> map = new HashMap<>();
map.put("username", "Bill");
map.put("occupation", "Student");
map.put("age", "22");
map.put("DOB", "" + new Date(System.currentTimeMillis()));
HttpResponse response = client.postRequest("/api/users", map);
client.printResponse(response);
现在我想用删除和更新做类似的事情,但不知道从哪里开始任何帮助会很棒
答案 0 :(得分:2)
使用适当的@Path
,@Delete
和@Put
注释,并以与@Post
类似的方式实施这些方法。