如何基于已实现的HTTP Get/Post代码编写Delete、Put请求?
Hey there! Let's walk through how to adapt your existing POST code to handle DELETE and PUT requests, with a focus on the ID-based deletion you need.
Adjusting POST Code to DELETE (ID-Based Deletion)
First, let's cover the key changes you'll need to make, plus important considerations for missing pieces:
Core Modifications
Change the HTTP Request Method
Swap out thePOSTmethod withDELETEin your code. For example, if you're usingHttpURLConnection, updateconn.setRequestMethod("POST")toconn.setRequestMethod("DELETE"). If you're using a library like OkHttp, adjust the request method toDELETE.Pass the Target ID Correctly
RESTful best practice for deletion is to embed the ID directly in the URL path (e.g.,/api/your-resource/16instead of sending it in the request body). So instead of your original POST URL (like/api/your-resource), modify it to include the ID:// Original POST URL URL url = new URL("https://your-api-domain/api/your-resource"); // Modified DELETE URL with ID URL url = new URL("https://your-api-domain/api/your-resource/16");If your backend expects the ID as a query parameter (e.g.,
/api/your-resource?id=16), adjust the URL accordingly instead.Remove Request Body Logic
Unlike POST, DELETE requests rarely require a request body (most REST APIs follow this convention). So you can remove all code that writes data to the request output stream. ForHttpURLConnection, this means skippingconn.setDoOutput(true)(or setting it tofalse), and removing theOutputStreamwriting block.
Missing Pieces & Considerations
- Backend Interface Confirmation: Double-check your API docs to confirm how the ID should be passed (path param, query param, or request body—though request body for DELETE is non-standard).
- Response Handling: DELETE has specific HTTP status codes you should handle:
204 No Content: Success (no response body returned)404 Not Found: The resource with ID 16 doesn't exist403 Forbidden: You don't have permission to delete the resource
- Request Headers: Ensure you're carrying over any required headers from your POST request (like
Authorizationtokens,Content-Type, etc.)—these are often needed for authentication/validation. - Error Handling: Add logic to catch network exceptions, timeouts, or unexpected response codes to make your code robust.
Example Modified DELETE Code (Java HttpURLConnection)
If your original POST code looks like this:
URL url = new URL("https://your-api-domain/api/your-resource"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); // Write POST body String jsonBody = "{\"name\": \"test\", \"desc\": \"test\", ...}"; try (OutputStream os = conn.getOutputStream()) { byte[] input = jsonBody.getBytes("utf-8"); os.write(input, 0, input.length); } // Handle response int responseCode = conn.getResponseCode(); // ... rest of response handling
Your modified DELETE code would be:
URL url = new URL("https://your-api-domain/api/your-resource/16"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("DELETE"); conn.setRequestProperty("Authorization", "Bearer your-token"); // Keep required headers conn.setDoOutput(false); // No request body needed // Handle response int responseCode = conn.getResponseCode(); switch(responseCode) { case HttpURLConnection.HTTP_NO_CONTENT: System.out.println("Resource with ID 16 deleted successfully"); break; case HttpURLConnection.HTTP_NOT_FOUND: System.out.println("Resource with ID 16 does not exist"); break; default: System.out.println("Delete failed with code: " + responseCode); }
Adjusting POST Code to PUT Requests
PUT is used to update an existing resource (often ID-based, similar to DELETE). Here's what to change:
Core Modifications
Change the HTTP Method to
PUT
Update the request method fromPOSTtoPUT(same way you did for DELETE).Embed the Target ID in the URL
Just like DELETE, include the resource ID in the URL path (e.g.,/api/your-resource/16) to specify which resource to update.Keep (or Adjust) the Request Body
Unlike DELETE, PUT requires a request body with the updated resource data (thename,desc,reward, etc. parameters you provided). You can reuse most of your POST body-writing logic, but update the JSON payload to reflect the new values you want to set.
Key Notes
- Idempotency: PUT is designed to be idempotent—sending the same request multiple times should have the same effect (unlike POST). Ensure your payload reflects the full state of the resource (or check if your API supports partial updates with PATCH instead).
- Response Status Codes: Watch for
200 OK(update successful),201 Created(if the ID didn't exist and the API created it), or404 Not Found(resource doesn't exist).
Example PUT Code Snippet
URL url = new URL("https://your-api-domain/api/your-resource/16"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Bearer your-token"); conn.setDoOutput(true); // Write updated resource data String updatedJsonBody = "{\"name\": \"updated-test\", \"desc\": \"updated-desc\", \"reward\":\"2.00\", \"sched\":\"2018-04-05T11:49:51+08:00\"}"; try (OutputStream os = conn.getOutputStream()) { byte[] input = updatedJsonBody.getBytes("utf-8"); os.write(input, 0, input.length); } // Handle response int responseCode = conn.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { System.out.println("Resource updated successfully"); } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND) { System.out.println("Resource with ID 16 not found"); }
内容的提问来源于stack exchange,提问作者user9551058

