【问题标题】:How Do I make a HTTP Delete/Update Request?如何发出 HTTP 删除/更新请求?
【发布时间】:2015-11-09 10:38:52
【问题描述】:

现在我有一个名为 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);

现在我想用删除和更新做类似的事情,但不知道从哪里开始,任何帮助都会很棒

【问题讨论】:

    标签: java http restful-url http-delete


    【解决方案1】:

    使用适当的@Path@Delete@Putannotations 并以与@Post 类似的方式实现这些方法。

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多