Skip to content
The Chat Archive
claude-sonnet-4-20250514· Anthropic LMArena Human Preference 140K

Post api Java example

  1. User

    Post api Java example

  2. Assistant

    Here's a Java example for making a POST API request using different approaches:

    Using HttpURLConnection (Built-in Java)

    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    
    public class PostApiExample {
        public static void main(String[] args) {
            try {
                URL url = new URL("https://jsonplaceholder.typicode.com/posts");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                
                // Set request method and headers
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Accept", "application/json");
                connection.setDoOutput(true);
                
                // JSON payload
                String jsonPayload = """
                    {
                        "title": "Sample Post",
                        "body": "This is a sample post body",
                        "userId": 1
                    }
                    """;
                
                // Write request body
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
                
                // Read response
                int responseCode = connection.getResponseCode();
                System.out.println("Response Code: " + responseCode);
                
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println("Response: " + response.toString());
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Using Apache HttpClient

    First, add the dependency to your pom.xml:

    <dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.2.1</version>
    </dependency>
    
    import org.apache.hc.client5.http.classic.methods.HttpPost;
    import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
    import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
    import org.apache.hc.client5.http.impl.classic.HttpClients;
    import org.apache.hc.core5.http.io.entity.StringEntity;
    import org.apache.hc.core5.http.io.entity.EntityUtils;
    
    public class PostApiHttpClient {
        public static void main(String[] args) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost("https://jsonplaceholder.typicode.com/posts");
                
                // Set headers
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setHeader("Accept", "application/json");
                
                // JSON payload
                String jsonPayload = """
                    {
                        "title": "Sample Post",
                        "body": "This is a sample post body",
                        "userId": 1
                    }
                    """;
                
                // Set request body
                StringEntity entity = new StringEntity(jsonPayload);
                httpPost.setEntity(entity);
                
                // Execute request
                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    System.out.println("Status Code: " + response.getCode());
                    String responseBody = EntityUtils.toString(response.getEntity());
                    System.out.println("Response: " + responseBody);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Using OkHttp

    Add the dependency:

    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>
    
    import okhttp3.*;
    import java.io.IOException;
    
    public class PostApiOkHttp {
        public static void main(String[] args) {
            OkHttpClient client = new OkHttpClient();
            
            String jsonPayload = """
                {
                    "title": "Sample Post",
                    "body": "This is a sample post body",
                    "userId": 1
                }
                """;
            
            RequestBody body = RequestBody.create(
                jsonPayload, 
                MediaType.get("application/json; charset=utf-8")
            );
            
            Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
            
            try (Response response = client.newCall(request).execute()) {
                System.out.println("Status Code: " + response.code());
                System.out.println("Response: " + response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    Each approach has its benefits: HttpURLConnection is built into Java, Apache HttpClient offers more features and flexibility, and OkHttp is lightweight with a clean API. Choose based on your project requirements and dependencies.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.