how to post http request java code example
Example 1: Post Request Example in Java
@BeforeAll
public static void init(){
RestAssured.baseURI = "http://........." ;
RestAssured.port = 8000 ;
RestAssured.basePath = "/api" ;
}
String myBodyData = "{\n" +
" \"name\" : \"Adam\",\n" +
" \"gender\": \"Male\",\n" +
" \"phone\": 6234567890\n" +
"}" ;
System.out.println("myBodyData = " + myBodyData);
given()
.contentType( ContentType.JSON )
.body(myBodyData)
.log().all().
when()
.post("/spartans").
then()
.log().all()
.statusCode( is(201) )
.contentType(ContentType.JSON)
.body("success", is ("A Spartan is Born!"))
.body("data.name", is ("Adam"))
;
Example 2: http java.net post
package com.zetcode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
public class HttpClientPost {
public static void main(String[] args) throws IOException, InterruptedException {
var values = new HashMap<String, String>() {{
put("name", "John Doe");
put ("occupation", "gardener");
}};
var objectMapper = new ObjectMapper();
String requestBody = objectMapper
.writeValueAsString(values);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/post"))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}