4

I am writing one Java application where I am calling one REST API patch operation using HttpURLConnection . I got to know that HttpURLConnection doesnt support PATCH operation.

I tried other suggestions mentioned in the other question HttpURLConnection Invalid HTTP method: PATCH

However, nothing worked for me.

Solution 1:

conn.setRequestProperty("X-HTTP-Method-Override", "PATCH"); conn.setRequestMethod("POST");

Not working on my dev server.

Solution 2:

private static void allowMethods(String... methods) {
        try {
            Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

            methodsField.setAccessible(true);

            String[] oldMethods = (String[]) methodsField.get(null);
            Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
            methodsSet.addAll(Arrays.asList(methods));
            String[] newMethods = methodsSet.toArray(new String[0]);

            methodsField.set(null/*static field*/, newMethods);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

the above solution worked, but foritfy is reporting the issue for the method setAccessible(). Can we use setAccessible() method on production? I mean will the above solution work on production environment.

is there anyway I can implement Patch operation using HttpURLConnection . Please suggest.

user31601
  • 2,482
  • 1
  • 12
  • 22
  • Is there a particular reason why you're opposed to using a more up-to-date library such as [Apache HTTP Components](https://hc.apache.org/)? This supports PATCH directly. – user31601 Jul 17 '18 at 10:51

0 Answers0