代码之家  ›  专栏  ›  技术社区  ›  ZeissS

如何在groovy中指定请求中的内容类型?

  •  2
  • ZeissS  · 技术社区  · 14 年前

    我正在尝试使用groovyhttpbuilder发布到microsoftexchangewebservice(EWS)。我的问题是,我无法设置正确的请求内容类型。图书馆在这里似乎有自己的想法。

    有人有主意吗?

    干杯,

    这是我的密码:

        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 回复  |  直到 14 年前
        1
  •  1
  •   ZeissS    14 年前

    在阅读和调试代码时,我发现这是我目前的解决方法。不像我希望的那么漂亮:

    // 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
    }