首页 > 解决方案 > HttpURLConnection 错误:HTTP 方法 PATCH 无效

问题描述

我正在编写一个 Java 应用程序,我正在使用 HttpURLConnection 调用一个 REST API 补丁操作。我知道 HttpURLConnection 不支持 PATCH 操作。

我尝试了其他问题HttpURLConnection Invalid HTTP method: PATCH中提到的其他建议

然而,没有什么对我有用。

解决方案1:

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

不在我的开发服务器上工作。

解决方案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);
        }
    }

上述解决方案有效,但 foritfy 正在报告 setAccessible() 方法的问题。我们可以在生产中使用 setAccessible() 方法吗?我的意思是上述解决方案是否适用于生产环境。

无论如何我可以使用 HttpURLConnection 实现补丁操作。请建议。

标签: javahttpurlconnection

解决方案


推荐阅读