HttpPost httpPost = new HttpPost("https://example.com/api/resource"); String requestBody = "{ \"name\": \"John\", \"age\": 30 }"; httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpPost httpPost = new HttpPost("https://example.com/upload"); File file = new File("/path/to/file.jpg"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", new FileBody(file)); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost);In this example, a POST request is made to upload a file to the server. The request body is multipart/form-data, and the file is added as a part using the FileBody class. Package: org.apache.httpcomponents.httpclient