第十五章、groovy与web服务交互

郏经纬
2023-12-01

1、预览web services

  • REST(REpresentational State Transfer (REST))
  • RSS (Really Simple Syndication)
  • ATOM (RFC-4287)
  • XML Remote Procedure Call(XML-RPC) 它添加了上下文,所有它是有状态的
  • SOAP继续扩展XML-RPC,增加一些新特性,比如安全、事务、可靠消息

2、读取RSS 和ATOM

  • package com.jack.groovy.ch15
    
    import groovy.xml.Namespace
    
    /**
     * @author liangchen* @date 2020/12/6
     *
     */
    // 获取bbc的头三条消息
    def base = 'http://news.bbc.co.uk/rss/newsonline_uk_edition/'
    
    def url = base + 'front_page/rss091.xml'
    
    println 'The top three news items today:'
    //其实就是一个xml文件
    def items = new XmlParser().parse(url).channel[0].item
    for (item in items[0..2]) {
        // 标题
        println item.title.text()
        //详情地址url
        println item.link.text()
        // 描述
        println item.decription.text()
        println '---------------'
    }
    // RSS 结构
    //        <rss ...>
    //
    //          <channel>
    //
    //              ...
    //
    //              <item>
    //
    //                  <title>...</title>
    //
    //                  <description>...</description>
    //
    //                   <link>...</link>
    //
    //                    ...
    
    // 使用Atom feed解析
    def urlAtom = 'http:/www.ibm.com/developerworks/views/java/rss' +
            'libraryview.jsp?feed_by=atom'
    def atom = new Namespace('http://www.w3.org/2005/Atom')
    def numEntries = 3
    def entries = new XmlParser().parse(url)[atom.entry][0..<numEntries]
    def len = "dd mmm yyyy ".size()
    def summaries = entries.collect {
        it[atom.published].text()[0..<len] +
                (it[atom.summary].text().contains('Groovy') ? '*' : ' ')+
                it[atom.title].text()
    }
    println summaries.join("\n")
    
    // Atom 格式结构
    //        <feed xmlns="http://www.w3.org/2005/Atom">
    //
    //            ...
    //
    //            <entry>
    //
    //                  <title>Java.next: The Java.next languages</title>
    //
    //                      ...
    
    
    

3、使用REST的API

4、使用XML-RPC

5、应用SOAP

  • SOAP 扩展XML-RPC的功能
    • 一方面是数据类型(datatypes)
    • WSDL(Web Services Definition Language ) : 描述SOAP信息

5.1、Groovy常规使用SOAP

  • package com.jack.groovy.ch15
    
    /**
     * @author liangchen* @date 2020/12/6
     */
    
    import groovy.xml.Namespace
    
    
    
    def url  = 'http://www.webservicex.net/CurrencyConvertor.asmx?WSDL'
    
    def wsdl = new Namespace('http://schemas.xmlsoap.org/wsdl/','wsdl')
    
    def doc  = new XmlParser().parse(url)
    
    
    
    println doc[wsdl.portType][wsdl.operation].'@name'
    
    
    // 使用 Conversion Rate SOAP服务
    // 使用模板生成数据
    import groovy.text.SimpleTemplateEngine as STE
    import groovy.xml.Namespace
    def file = new File('data/conv.templ.xml')
    def template = new STE().createTemplate(file)
    def params = [from:'USD', to:'EUR']
    def request = template.make(params).toString().getBytes('UTF-8')
    
    // 定义请求
    url = 'http://www.webservicex.net/CurrencyConvertor.asmx'
    def conn = new URL(url).openConnection()
    def reqProps = [
            'Content-Type' : 'text/xml; charset=UTF-8',
            'SOAPAction' : 'http://www.webserviceX.NET/ConversionRate',
            'Accept': 'application/soap+xml, text/*'
    ]
    reqProps.each { key, value -> conn.addRequestProperty(key, value) }
    conn.requestMethod = 'POST'
    conn.doOutput = true
    // 发送请求
    conn.outputStream << new ByteArrayOutputStream(request)
    
    // 处理请求响应数据
    if (conn.responseCode != conn.HTTP_OK) {
     println "Error - HTTP:${conn.responseCode}"
     return
    }
    def resp = new XmlParser().parse(conn.inputStream)
    def serv = new Namespace('http://www.webserviceX.NET/')
    def result = serv.ConversionRateResult
    print "Current USD to EUR conversion rate: "
    println resp.depthFirst().find{result == it.name()}.text()
    

5.2、使用HTTPBuilder简化使用SOAP

  • @Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.2')
    import groovyx.net.http.RESTClient
    import static  groovyx.net.http.ContentType.XML
    
    def base = 'http://www.webserviceX.NET/CurrentConvertor.asmx'
    def soapEnv = 'http://www.w3.org/2003/05/soap-envelope'
    def contentType = 'application/soap+xml;charset=UTF-8'
    new RESTClient(base).with{
        parser.'application/soap+xml' = parser.'applicaiton/xml'
        headers = ['Content-Type' : contentType]
        post(requestContentType:XML,body: {
            'soap:Envelope'('xmlns:soap': soapEnv){
                'soap:Body'{
                    ConversionRate(xmlns: 'http://www.webserviceX.NET/'){
                        FromCurrency('USD')
                        ToCurrency('EUR')
    
                    }
                }
            }
        }){resp, data ->
            assert  resp.status ==200
            println data.text()
        }
    }
    

5.3、使用groovy-wslite 简化使用SOAP

  • @Grab('com.github.groovy-wslite:groovy-wslite:1.1.0')
    
    import wslite.soap.SOAPClient
    
    
    
    def url = 'http://www.webservicex.net/CurrencyConvertor.asmx?WSDL'
    
    def client = new SOAPClient(url)
    
    def action = "http://www.webserviceX.NET/ConversionRate"
    
    def response = client.send(SOAPAction: action) {
    
        body {
    
            ConversionRate(xmlns: 'http://www.webserviceX.NET/') {
    
                FromCurrency('USD')
    
                ToCurrency('EUR')
    
            }
    
        }
    
    }
    
    assert response.httpResponse.statusCode == 200
    
    println response.ConversionRateResponse.ConversionRateResult
    
     切换使用SOAP 1.2
    @Grab('com.github.groovy-wslite:groovy-wslite:1.1.0')
    
    import wslite.soap.*
    
    
    
    def url = 'http://www.webserviceX.NET/CurrencyConvertor.asmx?WSDL'
    
    def client = new SOAPClient(url)
    
    def response = client.send {
    
        version SOAPVersion.V1_2
    
        body {
    
            ConversionRate(xmlns: 'http://www.webserviceX.NET/') {
    
                FromCurrency('USD')
    
                ToCurrency('EUR')
    
            }
    
        }
    
    }
    
    assert response.httpResponse.statusCode == 200
    
    println response.ConversionRateResponse.ConversionRateResult
    

6、总结

 类似资料: