Home > Software design >  How to make patch http request in groovy
How to make patch http request in groovy

Time:05-31

Why its not works ?

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

returns error = java.net.ProtocolException: Invalid HTTP method: PATCH

CodePudding user response:

old java HttpUrlConnection.setRequestMethod() does not support patch method:

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 

however there is a trick - in groovy you could set protected property value and there is a property method

https://docs.oracle.com/javase/10/docs/api/java/net/HttpURLConnection.html#method

so you could change the code:

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