user4274473
user4274473

Reputation:

How Do I make a HTTP Delete/Update Request?

Right Now I have a Restful Web service called Users.java, That fake adds a user to a fake database

@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
    }

}

it is called using the Post request here, these are examples

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);

Now I want to do something similar with Delete and Update but dont know where to start any help would be great

Upvotes: 0

Views: 312

Answers (1)

BetaRide
BetaRide

Reputation: 16844

Use appropriate @Path, @Delete and @Putannotations and implement the methods in a similar way you did for @Post.

Upvotes: 2

Related Questions