How do I send requests using different HTTP Methods with HttpClient?

Java 11 introduced the HttpClient API to simplify and modernize HTTP communications. This API supports sending requests using different HTTP methods (GET, POST, PUT, DELETE, etc.). Below is an explanation and example of how to perform these operations.

1. Setup

You will use the HttpClient and related classes from java.net.http package:

  • HttpClient – To execute HTTP requests.
  • HttpRequest – To construct and describe HTTP requests.
  • HttpResponse – To handle HTTP responses.

2. Example Code

Here’s how you can send HTTP requests with different methods using HttpClient in Java 11.

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;

public class HttpClientMethodExample {
   public static void main(String[] args) {
      try {
         // Create an HttpClient instance
         HttpClient httpClient = HttpClient.newHttpClient();

         // Example: GET Request
         HttpRequest getRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .GET() // Default is GET, this is optional
                 .build();
         HttpResponse<String> getResponse = httpClient.send(getRequest, BodyHandlers.ofString());
         System.out.println("GET Response: " + getResponse.body());

         // Example: POST Request
         HttpRequest postRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts"))
                 .POST(BodyPublishers.ofString("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"))
                 .header("Content-Type", "application/json")
                 .build();
         HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
         System.out.println("POST Response: " + postResponse.body());

         // Example: PUT Request
         HttpRequest putRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .PUT(BodyPublishers.ofString("{\"id\":1,\"title\":\"updated\",\"body\":\"new content\",\"userId\":1}"))
                 .header("Content-Type", "application/json")
                 .build();
         HttpResponse<String> putResponse = httpClient.send(putRequest, BodyHandlers.ofString());
         System.out.println("PUT Response: " + putResponse.body());

         // Example: DELETE Request
         HttpRequest deleteRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .DELETE()
                 .build();
         HttpResponse<String> deleteResponse = httpClient.send(deleteRequest, BodyHandlers.ofString());
         System.out.println("DELETE Response Code: " + deleteResponse.statusCode());

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

3. Explanation

  1. HttpClient Creation: The HttpClient instance is reusable for making multiple requests.
  2. GET Request:
    • Use .GET() method to send a GET request.
    • Response is parsed as a String using BodyHandlers.ofString().
  3. POST Request:
    • Use .POST(BodyPublishers.ofString(content)) to send a POST request with a payload.
    • Set the Content-Type header for JSON or other content types.
  4. PUT Request:
    • Use .PUT(BodyPublishers.ofString(content)) for PUT requests with a payload.
    • Similar to POST, set the proper headers.
  5. DELETE Request:
    • Use .DELETE() to send DELETE requests.
    • Rarely includes a body; that’s why no publisher is used.
  6. Error Handling:
    • Be sure to include error handling for exceptions such as IOException and InterruptedException.

4. Output Example

If you run the code using the example endpoints, the output might look something like this:

GET Response: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
POST Response: {
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}
PUT Response: {
  "id": 1,
  "title": "updated",
  "body": "new content",
  "userId": 1
}
DELETE Response Code: 200

5. Notes

  • You’ll need an API endpoint that supports CRUD operations for realistic testing.
  • Avoid hardcoding URIs in production; keep them configurable.
  • Handle response status codes appropriately for error cases (like 404, 500).

This approach provides a clean and modern way to work with HTTP in Java!

How do I create and delete a file in JDK 7?

In this example you’ll learn how to create and delete a file. Using the new Files class helper from the JDK 7 you can create a file using the Files.createFile(Path) method. To delete a file you can use the Files.delete(Path) method.

Before create a file and delete a file we can check to see if the file exists or not using the Files.exists(Path) method. In the code snippet below we’ll create a file when the file is not exist. And we’ll delete the file if the file exists.

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateDeleteFile {
    public static void main(String[] args) {
        try {
            // Create a config.cfg file under D:Temp directory.
            Path path = Paths.get("F:/Temp/config.cfg");
            if (!Files.exists(path)) {
                Files.createFile(path);
            }

            // Delete the path.cfg file specified by the Path.
            if (Files.exists(path)) {
                Files.delete(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I delete entity object in JPA?

The following code example show you how to delete or remove entity object from database using JPA. The first class that we are going to create is ArtistDaoImpl which implements ArtistDao. This DAO class handles the delete process either by the entity ID or by the entity object itself. We define the delete process in deleteById(Long id) and delete(Artist artist) methods.

In those methods we call the EntityManager.remove() method. This method of EntityManager will take care of removing the entity object from our database. Let’s see the DAO code below:

package org.kodejava.jpa.dao;

import org.kodejava.jpa.entity.Artist;

import java.util.List;

public interface ArtistDao {
    Artist findById(Long id);

    void save(Artist artist);

    void update(Artist artist);

    List<Artist> getArtists();

    void deleteById(Long id);

    void delete(Artist artist);
}
package org.kodejava.jpa.dao.impl;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;

public class ArtistDaoImpl implements ArtistDao {
    private final EntityManager manager;

    public ArtistDaoImpl(EntityManager manager) {
        this.manager = manager;
    }

    /**
     * Find Artist based on the entity id.
     *
     * @param artistId the artist id.
     * @return Artist.
     * @throws EntityNotFoundException when no artist is found.
     */
    public Artist findById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist == null) {
            throw new EntityNotFoundException("Can't find Artist for ID "
                    + artistId);
        }
        return artist;
    }

    @Override
    public void save(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    /**
     * Update Artist information.
     *
     * @param artist an Artist to be updated.
     */
    @Override
    public void update(Artist artist) {
        manager.getTransaction().begin();
        manager.merge(artist);
        manager.getTransaction().commit();
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public List<Artist> getArtists() {
        Query query = manager.createQuery("select a from Artist a", Artist.class);
        return query.getResultList();
    }

    /**
     * Delete artist by their id.
     *
     * @param id the artist id.
     */
    @Override
    public void deleteById(Long id) {
        Artist artist = manager.find(Artist.class, id);
        if (artist != null) {
            manager.getTransaction().begin();
            manager.remove(artist);
            manager.getTransaction().commit();
        }
    }

    /**
     * Delete artist entity.
     *
     * @param artist the object to be deleted.
     */
    @Override
    public void delete(Artist artist) {
        manager.getTransaction().begin();
        manager.remove(artist);
        manager.getTransaction().commit();
    }
}

After defining the delete methods in the ArtistDao class we create a simple program to demonstrate both of them. In this program we start by create the EntityManagerFactory object from the defined persistence unit in the persistence.xml file. Then we create the EntityManager object, and we pass it to our ArtistDaoImpl object. And then we call the delete methods to remove entity from the database.

To show you the result of the delete process we print out the artist data before and after the delete method is called.

package org.kodejava.jpa;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.dao.impl.ArtistDaoImpl;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class EntityRemoveDemo {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
                Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager manager = factory.createEntityManager();

        ArtistDao dao = new ArtistDaoImpl(manager);
        System.out.println("Before Delete:");
        printArtists(dao.getArtists());

        // Remove artist with ID = 1.
        dao.deleteById(1L);

        // Remove artist with ID = 2.
        Artist artist = dao.findById(2L);
        dao.delete(artist);

        System.out.println("After Delete:");
        printArtists(dao.getArtists());
    }

    private static void printArtists(List<Artist> artists) {
        for (Artist artist : artists) {
            System.out.println("Artist = " + artist);
        }
    }
}

Here is the result of our code snippet. It shows the number of records before and after the delete process.

Before Delete:
Artist = Artist{id=1, name='Bon Jovi'}
Artist = Artist{id=2, name='Mr. Big'}
Artist = Artist{id=3, name='Metallica'}
After Delete:
Artist = Artist{id=3, name='Metallica'}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I remove some characters from a StringBuffer?

The example below show you to remove some elements of the StringBuffer. We can use the delete(int start, int end) method call to remove some characters from the specified start index to end end index. We can also remove a character at the specified index using the deleteCharAt(int index) method call.

package org.kodejava.lang;

public class StringBufferDelete {
    public static void main(String[] args) {
        String text = "Learn Java by Examples";

        // Creates a new instance of StringBuffer and initialize
        // it with some text.
        StringBuffer buffer = new StringBuffer(text);
        System.out.println("Original text  = " + buffer);

        // We'll remove a sub string from this StringBuffer starting
        // from the first character to the 10th character.
        buffer.delete(0, 10);
        System.out.println("After deletion = " + buffer);

        // Removes a char at a specified index from the StringBuffer.
        // In the example below we remove the last character.
        buffer.deleteCharAt(buffer.length() - 1);
        System.out.println("Final result   = " + buffer);
    }
}

Output of the program is:

Original text  = Learn Java by Examples
After deletion =  by Examples
Final result   =  by Example

How do I delete persistent object in Hibernate?

Continuing the previous example How do I get object from database in Hibernate?, we now add the delete function in our LabelService class.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

public class LabelService {
    public Label getLabel(Long id) {
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        // We get back Label object from database by calling the Session
        // object get() method and passing the object type and the object
        // id to be read.
        Label label = session.get(Label.class, id);
        session.getTransaction().commit();

        return label;
    }

    public void deleteLabel(Long id) {
        // Load the object to be deleted
        Label label = getLabel(id);

        // We get the current session and delete the Label object from 
        // database.
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.delete(label);
        session.getTransaction().commit();
    }
}
package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

import java.util.Date;

public class DeleteDemo {
    public static void main(String[] args) {
        LabelService service = new LabelService();

        // Creates a Label object we are going to store in the database.
        // We set the name and created date information.
        Label label = new Label();
        label.setName("Sony Music");
        label.setCreated(new Date());

        // Call the LabelManager saveLabel method.
        service.saveLabel(label);

        // Read the object back from database.
        label = service.getLabel(label.getId());
        System.out.println("Label = " + label);

        service.deleteLabel(label.getId());
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central