gpt4 book ai didi

java - 如何发出 HTTP 删除/更新请求?

转载 作者:行者123 更新时间:2023-12-02 04:13:06 26 4
gpt4 key购买 nike

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

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

最佳答案

使用适当的@Path@Delete@Put注释,并以与@类似的方式实现方法发布

关于java - 如何发出 HTTP 删除/更新请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33607313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com