The controling protocol already have this task:
https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-clearBrowserCache
And selenium v4+ have this implemented in its API:
driver.getDevTools().send(Network.clearBrowserCache());
For older versions of selenium it's still possible to call this method natively using underlying protocol:
private void clearCache(ChromeDriverService service, WebDriver driver) throws IOException {
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Network.clearBrowserCache");
commandParams.put("params", emptyMap());
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = service.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
httpClient.execute(request);
}
Note: for chromium you should use "/chromium/send_command"
endpoint, for chrome: "/goog/cdp/execute"
.
But as of my experience, these both work the same way in both chrome and chromium.