Resolving Invalid HTTP Method: PATCH in Java HttpURLConnection

Dec 08, 2025 · Programming · 8 views · 7.8

Keywords: Java | HttpURLConnection | PATCH | HTTP Method | X-HTTP-Method-Override

Abstract: This article discusses the issue of using the PATCH method with Java's HttpURLConnection, providing a workaround using the X-HTTP-Method-Override header, and explores alternative solutions including third-party libraries and modern Java HTTP clients.

Introduction

In Java development, when attempting to use non-standard HTTP methods like PATCH with HttpURLConnection, developers often encounter a ProtocolException: "Invalid HTTP method: PATCH". This article addresses this problem and provides effective solutions, with a focus on the X-HTTP-Method-Override workaround.

Primary Solution: Using X-HTTP-Method-Override Header

The most straightforward and widely accepted workaround is to use the X-HTTP-Method-Override header. This technique involves sending a POST request with an additional header that specifies the intended HTTP method, such as PATCH.

HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com").openConnection();
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestMethod("POST");
// Add code for setting request body, headers, and handling response

This approach is compatible with most servers that support HTTP method overriding and avoids the need for modifying internal Java classes.

Alternative Methods

Other solutions include:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch("http://example.com");
CloseableHttpResponse response = httpClient.execute(httpPatch);

This method is more robust and adheres to HTTP standards.

HttpRequest request = HttpRequest.newBuilder()
               .uri(URI.create("http://example.com"))
               .method("PATCH", HttpRequest.BodyPublishers.ofString("body"))
               .build();
// Use HttpClient to send the request

Conclusion

For applications using the legacy HttpURLConnection, the X-HTTP-Method-Override header is a practical and simple workaround to send PATCH requests. However, for new development, it is advisable to use third-party libraries like Apache Http-Components or the modern Java HTTP client to ensure better compatibility and adherence to HTTP protocols.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.