[Resolvido] Como fazer o parse de uma resposta SOAP pelo cliente gerado de um WSDL (Correios)

Boa tarde srs.

Estou procurando aprender a trabalhar com Web Services.

Já tentei usando Eclipse e Netbeans…

Criei o cliente a partir do WSDL dos correios:

Especificações: http://www.correios.com.br/webServices/PDF/SCPP_manual_implementacao_calculo_remoto_de_precos_e_prazos.pdf
WSDL: http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?WSDL

Consigo consumir a web service testando através do Web Service Explorer do Eclipse, apenas.

Agora gostaria de criar uma classe main para consumir a ws, e exibir os resultados. Usando system.out.println mesmo, só para aprender…

De cara consegui apenas imprimir a string da resposta, mas não a Soap Message.

Procurei também diversos tutoriais a respeito. Encontrei alguns, mas não descubro como aplicar, finalmente, ao meu app.

Pelo Netbeans, tentei arrastar do WebServices Instances pro método main, mas também não consegui fazer funcionar.

Pelo visto além de ser bem beginner com Web Services, ainda preciso achar como ler a resposta.

Desculpe a dúvida bem beginner… alguém pode me dar uma luz por onde começar, por favor?

Obrigado!

ConsomeWS:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.christian;

import java.math.BigDecimal;
import org.tempuri.CResultado;
import org.tempuri.CalcPrecoPrazo;
import org.tempuri.CalcPrecoPrazoWS;
import org.tempuri.CalcPrecoPrazoWSSoap;

/**
 *
 * @author macbokpro17pol
 */

public class ConsomeWS {

    private CalcPrecoPrazoWSSoap myCalcPrecoPrazoProxy; // nao usei
    
    
    public void init() {
        try {
            
            String nCdEmpresa = null;
            String sDsSenha = null;
            String nCdServico = "40010"; //sedex
            String sCepOrigem = "02022030";
            String sCepDestino = "27310020";
            String nVlPeso = "0.4";
            int nCdFormato = 1; // caixa
            BigDecimal nVlComprimento = new BigDecimal(16);
            BigDecimal nVlAltura = new BigDecimal(6);
            BigDecimal nVlLargura = new BigDecimal(16);
            BigDecimal nVlDiametro = new BigDecimal(0);
            String sCdMaoPropria = "S";
            BigDecimal nVlValorDeclarado = new BigDecimal(150);
            String sCdAvisoRecebimento = "S";
            
            CalcPrecoPrazoWS service = new CalcPrecoPrazoWS();
            myCalcPrecoPrazoProxy = service.getCalcPrecoPrazoWSSoap(); // TALVEZ ALGO ERRADO AQUI?
            
            CResultado resultado = myCalcPrecoPrazoProxy.calcPrecoPrazo(nCdEmpresa, sDsSenha, nCdServico, sCepOrigem, sCepDestino, nVlPeso, nCdFormato, nVlComprimento, nVlAltura, nVlLargura, nVlDiametro, sCdMaoPropria, nVlValorDeclarado, sCdAvisoRecebimento);
            
            System.out.println(resultado);
                    
            
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        
       
        }
    
    public static void main(String args[]) {
            ConsomeWS client = new ConsomeWS();
            client.init();
    }

}

Web Service: (em outro projeto)

package br.com.christian;

import javax.jws.WebService;

/**
 *
 * @author macbokpro17pol
 */
@WebService(serviceName = "CalcPrecoPrazoWS", portName = "CalcPrecoPrazoWSSoap", endpointInterface = "org.tempuri.CalcPrecoPrazoWSSoap", targetNamespace = "http://tempuri.org/", wsdlLocation = "WEB-INF/wsdl/CorreiosWS/CorreiosWS.wsdl")
public class CorreiosWS {

    public org.tempuri.CResultado calcPrecoPrazo(java.lang.String nCdEmpresa, java.lang.String sDsSenha, java.lang.String nCdServico, java.lang.String sCepOrigem, java.lang.String sCepDestino, java.lang.String nVlPeso, int nCdFormato, java.math.BigDecimal nVlComprimento, java.math.BigDecimal nVlAltura, java.math.BigDecimal nVlLargura, java.math.BigDecimal nVlDiametro, java.lang.String sCdMaoPropria, java.math.BigDecimal nVlValorDeclarado, java.lang.String sCdAvisoRecebimento) {
        //TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    public org.tempuri.CResultado calcPrecoPrazoData(java.lang.String nCdEmpresa, java.lang.String sDsSenha, java.lang.String nCdServico, java.lang.String sCepOrigem, java.lang.String sCepDestino, java.lang.String nVlPeso, int nCdFormato, java.math.BigDecimal nVlComprimento, java.math.BigDecimal nVlAltura, java.math.BigDecimal nVlLargura, java.math.BigDecimal nVlDiametro, java.lang.String sCdMaoPropria, java.math.BigDecimal nVlValorDeclarado, java.lang.String sCdAvisoRecebimento, java.lang.String sDtCalculo) {
        //TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    public org.tempuri.CResultado calcPreco(java.lang.String nCdEmpresa, java.lang.String sDsSenha, java.lang.String nCdServico, java.lang.String sCepOrigem, java.lang.String sCepDestino, java.lang.String nVlPeso, int nCdFormato, java.math.BigDecimal nVlComprimento, java.math.BigDecimal nVlAltura, java.math.BigDecimal nVlLargura, java.math.BigDecimal nVlDiametro, java.lang.String sCdMaoPropria, java.math.BigDecimal nVlValorDeclarado, java.lang.String sCdAvisoRecebimento) {
        //TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    public org.tempuri.CResultado calcPrecoData(java.lang.String nCdEmpresa, java.lang.String sDsSenha, java.lang.String nCdServico, java.lang.String sCepOrigem, java.lang.String sCepDestino, java.lang.String nVlPeso, int nCdFormato, java.math.BigDecimal nVlComprimento, java.math.BigDecimal nVlAltura, java.math.BigDecimal nVlLargura, java.math.BigDecimal nVlDiametro, java.lang.String sCdMaoPropria, java.math.BigDecimal nVlValorDeclarado, java.lang.String sCdAvisoRecebimento, java.lang.String sDtCalculo) {
        //TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    public org.tempuri.CResultado calcPrazo(java.lang.String nCdServico, java.lang.String sCepOrigem, java.lang.String sCepDestino) {
        //TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    public org.tempuri.CResultado calcPrazoData(java.lang.String nCdServico, java.lang.String sCepOrigem, java.lang.String sCepDestino, java.lang.String sDtCalculo) {
        //TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }
    
}

CONSOLE:

ant -f /Users/macbokpro17pol/NetBeansProjects/CorreiosWSClient -Djavac.includes=br/com/christian/ConsomeWS.java -Drun.class=br.com.christian.ConsomeWS run-single
init:
Deleting: /Users/macbokpro17pol/NetBeansProjects/CorreiosWSClient/build/built-jar.properties
deps-jar:
Updating property file: /Users/macbokpro17pol/NetBeansProjects/CorreiosWSClient/build/built-jar.properties
wsimport-init:
wsimport-client-CalcPrecoPrazo:
files are up to date
classLoader = java.net.URLClassLoader@5f5d40f
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@2528a1f1
wsimport-client-generate:
Compiling 1 source file to /Users/macbokpro17pol/NetBeansProjects/CorreiosWSClient/build/classes
compile-single:
run-single:
java.lang.NullPointerException
at br.com.christian.ConsomeWS.init(ConsomeWS.java:44)
at br.com.christian.ConsomeWS.main(ConsomeWS.java:59)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Você conseguiu, é isso?

Assumindo que sim, deixo aqui pra manter o registro:

Para criar um cliente de um web service qualquer, basta utilizar wsimport. Supondo que a estrutura do seu projeto contenha a pasta src, basta ir até a raiz do projeto e digitar o seguinte:

wsimport -keep -s src <endereço do serviço>

Vale lembrar que o wsimport é um aplicativo de linha de comando, e está localizado na mesma pasta que o javac.

[]'s

Oi Alexandre! Obrigado pela resposta.

Então, eu usei o WSIMPORT pelo Netbeans…

Essa parte, tudo ok…

Infelizmente eu não consegui, como voce pode ver na resposta do console, ele dava Null Point na linha que eu chamava o resultado…

Dei CLEAN & BUILD

O erro é o mesmo:
java.lang.NullPointerException
at br.com.christian.ConsomeWS.init(ConsomeWS.java:44)
at br.com.christian.ConsomeWS.main(ConsomeWS.java:59)
Java Result: 1

Essa linha é a linha que chama o resultado…

Pode me ajudar?

obrigado!

Consegui ter o resultado “errado” (String) mudando a linha para:

            CResultado resultado = service.getCalcPrecoPrazoWSSoap().calcPrecoPrazo(nCdEmpresa, sDsSenha, nCdServico, sCepOrigem, sCepDestino, nVlPeso, nCdFormato, nVlComprimento, nVlAltura, nVlLargura, nVlDiametro, sCdMaoPropria, nVlValorDeclarado, sCdAvisoRecebimento);

Resultado:
org.tempuri.CResultado@2bd9e282

Agora vou descobrir como pego os dados do soap retornado…

Não estou conseguindo entender a lógica das classes:
CResultado.java
CSerico.java
ArrayOfServico.java

Alguém pode me ajudar?

Segue:

CResultado.java:


package org.tempuri;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for cResultado complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="cResultado">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="Servicos" type="{http://tempuri.org/}ArrayOfCServico" minOccurs="0"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "cResultado", propOrder = {
    "servicos"
})
public class CResultado {

    @XmlElement(name = "Servicos")
    protected ArrayOfCServico servicos;

    /**
     * Gets the value of the servicos property.
     * 
     * @return
     *     possible object is
     *     {@link ArrayOfCServico }
     *     
     */
    public ArrayOfCServico getServicos() {
        return servicos;
    }

    /**
     * Sets the value of the servicos property.
     * 
     * @param value
     *     allowed object is
     *     {@link ArrayOfCServico }
     *     
     */
    public void setServicos(ArrayOfCServico value) {
        this.servicos = value;
    }

}

CServico.java:


package org.tempuri;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for cServico complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="cServico">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="Codigo" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         &lt;element name="Valor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="PrazoEntrega" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="ValorMaoPropria" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="ValorAvisoRecebimento" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="ValorValorDeclarado" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="EntregaDomiciliar" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="EntregaSabado" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="Erro" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         &lt;element name="MsgErro" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "cServico", propOrder = {
    "codigo",
    "valor",
    "prazoEntrega",
    "valorMaoPropria",
    "valorAvisoRecebimento",
    "valorValorDeclarado",
    "entregaDomiciliar",
    "entregaSabado",
    "erro",
    "msgErro"
})
public class CServico {

    @XmlElement(name = "Codigo")
    protected int codigo;
    @XmlElement(name = "Valor")
    protected String valor;
    @XmlElement(name = "PrazoEntrega")
    protected String prazoEntrega;
    @XmlElement(name = "ValorMaoPropria")
    protected String valorMaoPropria;
    @XmlElement(name = "ValorAvisoRecebimento")
    protected String valorAvisoRecebimento;
    @XmlElement(name = "ValorValorDeclarado")
    protected String valorValorDeclarado;
    @XmlElement(name = "EntregaDomiciliar")
    protected String entregaDomiciliar;
    @XmlElement(name = "EntregaSabado")
    protected String entregaSabado;
    @XmlElement(name = "Erro")
    protected String erro;
    @XmlElement(name = "MsgErro")
    protected String msgErro;

    /**
     * Gets the value of the codigo property.
     * 
     */
    public int getCodigo() {
        return codigo;
    }

    /**
     * Sets the value of the codigo property.
     * 
     */
    public void setCodigo(int value) {
        this.codigo = value;
    }

    /**
     * Gets the value of the valor property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getValor() {
        return valor;
    }

    /**
     * Sets the value of the valor property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setValor(String value) {
        this.valor = value;
    }

    /**
     * Gets the value of the prazoEntrega property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getPrazoEntrega() {
        return prazoEntrega;
    }

    /**
     * Sets the value of the prazoEntrega property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setPrazoEntrega(String value) {
        this.prazoEntrega = value;
    }

    /**
     * Gets the value of the valorMaoPropria property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getValorMaoPropria() {
        return valorMaoPropria;
    }

    /**
     * Sets the value of the valorMaoPropria property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setValorMaoPropria(String value) {
        this.valorMaoPropria = value;
    }

    /**
     * Gets the value of the valorAvisoRecebimento property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getValorAvisoRecebimento() {
        return valorAvisoRecebimento;
    }

    /**
     * Sets the value of the valorAvisoRecebimento property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setValorAvisoRecebimento(String value) {
        this.valorAvisoRecebimento = value;
    }

    /**
     * Gets the value of the valorValorDeclarado property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getValorValorDeclarado() {
        return valorValorDeclarado;
    }

    /**
     * Sets the value of the valorValorDeclarado property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setValorValorDeclarado(String value) {
        this.valorValorDeclarado = value;
    }

    /**
     * Gets the value of the entregaDomiciliar property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getEntregaDomiciliar() {
        return entregaDomiciliar;
    }

    /**
     * Sets the value of the entregaDomiciliar property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setEntregaDomiciliar(String value) {
        this.entregaDomiciliar = value;
    }

    /**
     * Gets the value of the entregaSabado property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getEntregaSabado() {
        return entregaSabado;
    }

    /**
     * Sets the value of the entregaSabado property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setEntregaSabado(String value) {
        this.entregaSabado = value;
    }

    /**
     * Gets the value of the erro property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getErro() {
        return erro;
    }

    /**
     * Sets the value of the erro property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setErro(String value) {
        this.erro = value;
    }

    /**
     * Gets the value of the msgErro property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getMsgErro() {
        return msgErro;
    }

    /**
     * Sets the value of the msgErro property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setMsgErro(String value) {
        this.msgErro = value;
    }

}

ArrayOfServico.java

package org.tempuri;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for ArrayOfCServico complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="ArrayOfCServico">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="cServico" type="{http://tempuri.org/}cServico" maxOccurs="unbounded" minOccurs="0"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfCServico", propOrder = {
    "cServico"
})
public class ArrayOfCServico {

    protected List<CServico> cServico;

    /**
     * Gets the value of the cServico property.
     * 
     * <p>
     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a <CODE>set</CODE> method for the cServico property.
     * 
     * <p>
     * For example, to add a new item, do as follows:
     * <pre>
     *    getCServico().add(newItem);
     * </pre>
     * 
     * 
     * <p>
     * Objects of the following type(s) are allowed in the list
     * {@link CServico }
     * 
     * 
     */
    public List<CServico> getCServico() {
        if (cServico == null) {
            cServico = new ArrayList<CServico>();
        }
        return this.cServico;
    }

}

Obrigado. :slight_smile:

RESOLVIDO!

ver linha 51

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/  
package br.com.christian;  
  
import java.math.BigDecimal;  
import java.util.ArrayList;
import java.util.List;
import org.tempuri.ArrayOfCServico;
import org.tempuri.CResultado;  
import org.tempuri.CServico;
import org.tempuri.CalcPrecoPrazo;  
import org.tempuri.CalcPrecoPrazoWS;  
import org.tempuri.CalcPrecoPrazoWSSoap;  
  
/** 
* 
* @author macbokpro17pol  
*/  
  
public class ConsomeWS {  
  
    private CalcPrecoPrazoWSSoap myCalcPrecoPrazoProxy; // nao usei  
      
      
    public void init() {  
        try {  
              
            String nCdEmpresa = null;  
            String sDsSenha = null;  
            String nCdServico = "40010"; //sedex  
            String sCepOrigem = "02022030";  
            String sCepDestino = "27310020";  
            String nVlPeso = "0.4";  
            int nCdFormato = 1; // caixa  
            BigDecimal nVlComprimento = new BigDecimal(16);  
            BigDecimal nVlAltura = new BigDecimal(6);  
            BigDecimal nVlLargura = new BigDecimal(16);  
            BigDecimal nVlDiametro = new BigDecimal(0);  
            String sCdMaoPropria = "S";  
            BigDecimal nVlValorDeclarado = new BigDecimal(150);  
            String sCdAvisoRecebimento = "S";  
              
            CalcPrecoPrazoWS service = new CalcPrecoPrazoWS();  
            //myCalcPrecoPrazoProxy = service.getCalcPrecoPrazoWSSoap(); // TALVEZ ALGO ERRADO AQUI?  
              
            CResultado resultado = service.getCalcPrecoPrazoWSSoap().calcPrecoPrazo(nCdEmpresa, sDsSenha, nCdServico, sCepOrigem, sCepDestino, nVlPeso, nCdFormato, nVlComprimento, nVlAltura, nVlLargura, nVlDiametro, sCdMaoPropria, nVlValorDeclarado, sCdAvisoRecebimento);
            System.out.println(resultado);  
            
            System.out.println("Resutado Valor: " + resultado.getServicos().getCServico().get(0).getValor());
            
           
              
        } catch (Exception e) {  
            e.printStackTrace();  
            System.exit(1);  
        }  
          
         
        }  
      
    public static void main(String args[]) {  
            ConsomeWS client = new ConsomeWS();  
            client.init();  
    }  
  
}  

Dê uma olhada: http://www.guj.com.br/java/285695-duvida-webservice#1555553

[]'s

Ta feito alexandre! Obrigado pela ajuda!

Agora o negócio ta pegando mesmo é aqui: http://www.guj.com.br/java/293317-cliente-web-service-a-partir-de-wsdl-complexa-sem-especificacao

Como mudo pra resolvido?

abs