How to specify content type in request in groovy?

让人想犯罪 __ 提交于 2019-12-12 09:59:36

问题


i'm trying to use the groovy httpbuilder to make a post to the microsoft exchange webservice (EWS). My problem is, I'm unable to set the proper request content-type. The library seems to have its own mind here.

Does anyone have an idea?

Cheers, Stephan

Here is my code:

    url = "http://exchangeserver/ews/Exchange.asmx"
    p_body = "<soap request >...";
    p_contentType = "text/xml; charset=utf-8"
    customHeaders = ["SOAPAction":"LONG_URL"]

    def http = new HTTPBuilder(url);
    http.auth.basic(authMap.username, authMap.password)

    // contentType: p_contentType,
    http.request( POST ) 
    {
        contentType = ContentType.TEXT // We dont want to get the response parsed
        headers['Accept'] = "*/*"; // Just make sure we accept everything

        // Support additional headers
        for (x in customHeaders) {
            headers[x] = customHeaders[x]   
        }


        /// Exchange expects "text/xml; charset=utf-8" and nothing else :(

//  This sends text/plain
//      body = p_body
//      requestContentType = p_contentType

        // This sends application/xml, not my "text/xml; charset=utf-8" content-type.
            send p_contentType, p_body 

        // a successfull request should be "logged" ;)
        response.success = { resp, xml ->
            println xml
        }
    }

回答1:


Well, reading and debugging the code, I found this to be my current workaround / solution. Not as beautifull as I hoped:

// We overwrite the default text/xml encoder,
// because it replaces our contentType with 'application/xml'
// But Exchange only likes 'text/xml; charset=utf-8'
http.encoder.'text/xml' = {
    body -> def se = new StringEntity(body, "utf-8")
    se.setContentType("text/xml; charset=utf-8")
    return se
}


来源:https://stackoverflow.com/questions/3493195/how-to-specify-content-type-in-request-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!