Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > spring-ws


Автор: ratzko 6.8.2008, 01:10
начал изучать spring web services

написал следующий код: 

Код

public class Client extends WebServiceGatewaySupport {
    
    private Resource request;
    private String action;
    
    public void setRequest(Resource request) {
        this.request = request;
    }
    
    public void setAction(String action) {
        this.action = action;
    }
    
    public void quotes() throws IOException {
        Source requestSource = new ResourceSource(request);
        StringResult result = new StringResult();
        getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, new SoapActionCallback(action), result);
        FileWriter writer = new FileWriter("settings.xml");
        writer.write(result.toString()
                    .replace("&lt;", "<")
                    .replace("&gt;", ">"));
        writer.close();
        System.out.println(result);
    }

    public static void main(String[] args) throws IOException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("webmedia-service.xml", Client.class);
        Client stockClient = (Client) applicationContext.getBean("stockClient");
        stockClient.quotes();
    }
    
}


Код

<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
            
    <bean id="stockClient" class="service.Client">
        <property name="defaultUri" value="http://www.webserviceX.NET/stockquote.asmx"/>
        <property name="request" value="classpath:quotesRequest.xml"/>
        <property name="action" value="http://www.webserviceX.NET/GetQuote"/>
        
    </bean>
</beans>


Код

<GetQuote xmlns="http://www.webserviceX.NET/">
    <symbol>GOOG</symbol>
</GetQuote>


получаю следующий XML: 

Код

<GetQuoteResponse xmlns="http://www.webserviceX.NET/">
    <GetQuoteResult>
        <StockQuotes>
            <Stock>
                <Symbol>GOOG</Symbol>
                <Last>479.85</Last>
                <Date>8/5/2008</Date>
                <Time>4:00pm</Time>
                <Change>+16.85</Change>
                <Open>467.89</Open>
                <High>480.08</High>
                <Low>466.33</Low>
                <Volume>3584321</Volume>
                <MktCap>150.6B</MktCap>
                <PreviousClose>463.00</PreviousClose>
                <PercentageChange>+3.64%</PercentageChange>
                <AnnRange>412.11 - 747.24</AnnRange>
                <Earns>15.216</Earns>
                <P-E>30.43</P-E>
                <Name>GOOGLE</Name>
            </Stock>
        </StockQuotes>
    </GetQuoteResult>
</GetQuoteResponse>



мне из етого XML'a нузно только зна4ение тэга <Last/>! как его мозно полу4ить?

Автор: ratzko 6.8.2008, 22:34
Как я понял мне надо вместо getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, new SoapActionCallback(action), result) исползовать getWebServiceTemplate().marshalSendAndReceive(..). Так ли это? И если так мозет кто-нибудь обяснить как этот метод использовать или дать примеры его использования!?

Автор: sarjsheff 11.8.2008, 10:44
Можно без маршалинга, просто отпарсить в DOM и вытянуть все что нужно. 


Код

        static public Document getDOM(String in) {
                    try {
                            InputStream ins = new ByteArrayInputStream(in.getBytes());
    
                            return getDOM(ins);
                    } catch (Exception pce) {
                            pce.printStackTrace();
                            return null;
                    }
            }
    
            static public Document getDOM(InputStream in) {
                    try {
                            DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
                            documentFactory.setNamespaceAware(true);
                            documentFactory.setValidating(false);
    
                            DocumentBuilder docBuilder = documentFactory.newDocumentBuilder();
                            // docBuilder.setEntityResolver(new NoEntityResolver());               
                            return docBuilder.parse(in);
                            } catch (Exception pce) {
                            pce.printStackTrace();
                            return null;
                    }
            }


У себя в коде.

Код

getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, new SoapActionCallback(action), result);
Document doc = getDOM(result.toString());
String Last = doc.getElementsByTagName("Last")[1].getNodeText();


Где то примерно так в doc.getElementsByTagName("Last")[1].getNodeText(); мог напутать не проверял. Смотри тут как с Documentом работать.

Автор: ratzko 11.8.2008, 10:47
Спасибо! Работает.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)