Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Acessando WS da Sefaz para NF-e
package br.com.syspdv.nfe.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.security.Security;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPMessage;
public class AcessaWsDaSefaz {
public static void AcessarWsComAutenticacao(String urlAddress, String envelope) {
try {
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
/*
* limpo propriedades
*/
System.clearProperty("javax.net.ssl.keyStore");
System.clearProperty("javax.net.ssl.keyStorePassword");
System.clearProperty("javax.net.ssl.trustStore");
/*
* dados do certificado do cliente
*/
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
System.setProperty("javax.net.ssl.keyStore", "C:/CERTIFICADO_FULL.pfx");
System.setProperty("javax.net.ssl.keyStorePassword", "123456");
/*
* dados do certificado do servidor
*/
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", "C:/NfeCacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "123456");
/* Url do WebService */
URL url = new URL(urlAddress);
/* tipo de mensagem: SOAP */
MimeHeaders header = new MimeHeaders();
header.addHeader("Content-Type", "application/soap+xml");
/* monta a mensagem SOAP */
MessageFactory factory = MessageFactory
.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage message = factory.createMessage(header,
new ByteArrayInputStream(envelope.getBytes()));
/* instancia uma conexao SOAP */
SOAPConnection conSoap = SOAPConnectionFactory.newInstance()
.createConnection();
/* Envia a mensagem SOAP ao WebService */
SOAPMessage resWs = conSoap.call(message, url);
/* Mostra a mensagem de retorno */
ByteArrayOutputStream out = new ByteArrayOutputStream();
resWs.writeTo(out);
System.out.println("out :\n" + out.toString());
} catch (Exception ex) {
System.out.println("Erro: " + ex.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment