Search code examples
javagroovysyntaxmapshttpbuilder

Groovy HttpBuilder getting header's value


I'am trying to get headers in from HttpBuilder and confused about difference between using headers."Header name" and headers["Header name"]

HTTPBuilder builder = new HTTPBuilder();
builder.setUri("https://stackoverflow.com/")
builder.request(Method.GET) {
    response.success = { resp ->
        def header1 = resp.headers."Strict-Transport-Security"
        def header2 = resp.headers["Strict-Transport-Security"]
        println("Header toSting: ${header1}, Header class: ${header1.class}") //result: Header toSting: max-age=15552000, Header class: class java.lang.String
        println("Header toSting: ${header2}, Header class: ${header2.class}") // result: Header toSting: Strict-Transport-Security: max-age=15552000, Header class: class org.apache.http.message.BufferedHeader
    }
}

So results are different. Can you explain how it works? I was sure that something."key" is the same as something["key"]


Solution

  • Depends on what you use those syntaxes on.

    If you use those syntaxes on a Map, you are right.

    But the headers field is not a Map, but a HeadersDecorator instance that provides those different syntaxes. Just click on the link to get to the respective JavaDoc.

    Using operators in Groovy is just about methods being called and you can even override them to change operator behavior. In the case of Map, getAt(Object) does the bracket syntax retrieval of the value, propertyMissing(String) does the dot notation retrieval of the value if there is no object property with that name.

    In case of the HeadersDecorator getAt(String) does the bracket syntax retrieval of the Header object and propertyMissing(String) does the dot notation retrieval of the value of the header if there is no object property with that name.