為什么它不起作用?
def post = new URL(url).openConnection();
post.setRequestMethod("PATCH");
post.setDoOutput(true);
post.setRequestProperty("Content-Type", "application/json");
post.getOutputStream().write(body.getBytes("UTF-8"));
def postRC = post.getResponseCode();
logger.info("Status code = ${postRC}");
回傳錯誤 =java.net.ProtocolException: Invalid HTTP method: PATCH
uj5u.com熱心網友回復:
舊的 java HttpUrlConnection.setRequestMethod() 不支持補丁方法:
https://docs.oracle.com/javase/10/docs/api/java/net/HttpURLConnection.html#setRequestMethod(java.lang.String)
public void setRequestMethod?(String method) throws ProtocolException
Set the method for the URL request, one of:
GET
POST
HEAD
OPTIONS
PUT
DELETE
TRACE
但是有一個技巧 - 在 groovy 中你可以設定受保護的屬性值并且有一個屬性method
https://docs.oracle.com/javase/10/docs/api/java/net/HttpURLConnection.html#method
所以你可以更改代碼:
def body = [test:123]
def post = new URL("http://httpbin.org/patch").openConnection();
post.method ="PATCH";
post.setDoOutput(true);
post.setRequestProperty("Content-Type", "application/json");
post.getOutputStream().withWriter("UTF-8"){ it << new groovy.json.JsonBuilder(body) }
def postRC = post.getResponseCode();
println "Status code = ${postRC}"
println post.getInputStream().getText("UTF-8")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483789.html
