Intern
What are HTTP methods?
sobes.tech AI
Answer from AI
HTTP methods (verbs or commands) define actions that can be performed on the resource specified in the request URI.
Main methods:
GET: Requests a representation of the specified resource. Request data is sent in the URL. Used to retrieve data.POST: Sends data to be processed to the specified resource. Request data is sent in the body. Used to create or update a resource.PUT: Replaces all current representations of the resource with the content of the request body. Used to update a resource.DELETE: Deletes the specified resource. Used to delete a resource.PATCH: Applies partial modifications to the resource.HEAD: Requests the same headers asGET, but without the response body.OPTIONS: Describes the HTTP methods supported by the server for the specified URL.
Properties of methods:
- Idempotency: Performing the same request multiple times results in the same resource state as performing it once. Idempotent methods:
GET,PUT,DELETE,HEAD,OPTIONS. Non-idempotent:POST,PATCH. - Safety: The request does not change the state of the resource on the server. Safe methods:
GET,HEAD,OPTIONS. Unsafe methods:POST,PUT,DELETE,PATCH.
// Example of a GET request in Java using HttpClient
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/resource"))
.GET() // Method
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
// Example of a POST request in Java
String postBody = "{\"name\":\"test\", \"value\":\"data\"}";
HttpRequest postRequest = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/resource"))
.POST(HttpRequest.BodyPublishers.ofString(postBody)) // Method
.header("Content-Type", "application/json")
.build();
HttpResponse<String> postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString());
System.out.println(postResponse.body());