如何在groovy中发出补丁http请求

ckocjqey  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(236)

为什么它不起作用?

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

z31licg0

z31licg01#

旧java HttpUrlConnection.setRequestMethod()不支持修补程序方法:
(Java语言字串)

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")

相关问题