java - 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 实现补丁操作。请建议。
解决方案
推荐阅读
- ios - 将具有单独时区的日期对象转换为 NSDate 的正确方法是什么
- google-play - Ubuntu:为谷歌播放音乐启用媒体键
- python - 运行时使用 dynamic_rnn 的 Tensorflow GPU 内存不足
- python - 每个套接字地址(协议/网络地址/端口)通常只允许使用一次,
- node.js - 错误:连接 ECONNREFUSED 127.0.0.1:5432 docker migrate
- terminology - BBDD 代表什么?
- javascript - 如何遍历对象文字数组?
- clojure - 原子交换存储无限惰性序列的原子
- facebook - 由于 CSP 错误,Facebook 登录无法在 Firefox 中运行
- airflow - 如何使用气流检查长时间运行的 http 任务的状态?