Reputation: 1256
I need to send an HTTP Patch request using a Java program. Can someone post a code snippet displaying how to do this?
Upvotes: 5
Views: 5539
Reputation: 11
This code works for me.
Imports here:
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
The PATCH method here:
public ResponseEntity<String> performPatchRequest(YourDataDTO dataDTO) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-API-KEY", "yourApiKey"); //if needed only
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("someData", dataDTO.getSomeData());
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
String url = "yourUrlHere;
// Create an HttpClient that supports the PATCH method
CloseableHttpClient httpClient = HttpClients.custom().build();
// Create a RestTemplate using the HttpClient
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate.exchange(url, HttpMethod.PATCH, requestEntity, String.class);
}
Upvotes: 0
Reputation: 21
Maybe this will help you:
Response response = request(webTarget).method("PATCH", entity);
Upvotes: 2