HttpPost httpPost = new HttpPost("https://www.example.com/api"); String requestBody = "{ \"name\": \"John\" }"; StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(entity);
HttpPost httpPost = new HttpPost("https://www.example.com/api"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("name", "John"); builder.addBinaryBody("file", new File("/path/to/file")); HttpEntity entity = builder.build(); httpPost.setEntity(entity);In this example, we create a new HttpPost object with the URL of the API. We create a MultipartEntityBuilder object, which allows us to add multiple parts to the POST request. We add a text body with the key "name" and value "John", and a binary body with the key "file" and the contents of a file located at "/path/to/file". We then build the HttpEntity with the builder and set it as the entity of the HttpPost request. Overall, setEntity method is crucial to set the body of the HTTP POST request in Java, and Apache HttpComponents provide different options depending on the content type that needs to be set.