java.net.HttpURLConnection は、HTTP Method PATCH を送信しようとすると、
Caused by: java.net.ProtocolException: Invalid HTTP method: PATCH
とエラーになってしまう。
これは、HttpURLConnection の setRequestMethod が、
以下のHTTPメソッドしか受け入れないからである。
GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE
Stackoverflow で以下を見つけたが、、
java - HttpURLConnection error: Invalid HTTP method PATCH - Stack Overflow
この Stackoverflow の Solution 2: の方法は、setRequestMethod が検証するメソッド名の配列 String を
リフレクションで、HttpURLConnection しか参照しない String methods に、
元の配列に許可したいメソッド名を追加する方法だ。
でもよくよく考えると、結局は HttpURLConnection が抱え持つ
String method に実行するメソッド名を検証してセットするだけだから、
PATCH を実行したければ、setRequestMethod で "PATCH" をセットするのではなく、
直接リフレクションで String method にセットすれば良い。
だから、以下のメソッドで充分なのである。
private static void setMethodForce(HttpURLConnection conn, String method){ try{ Field methodField = HttpURLConnection.class.getDeclaredField("method"); methodField.setAccessible(true); methodField.set(conn, method); }catch(NoSuchFieldException | IllegalAccessException e){ throw new IllegalStateException(e); } }
URL url = new URL("http://xxxx/xxxxx/xxxx"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setMethodForce(conn, "PATCH");