javax.xml.soap.SOAPConnection和java.mail

时间:2015-04-29 02:08:42

标签: java email ssl soap

在我们的系统(app)中,我们通过政府服务器托管的网络服务发送税务文件。我们通过以下方法发送此文件:

public SOAPMessage conecta(String xmlNfedados, URL url) throws SOAPException{
    SOAPMessage res = null; 

    try {
        MimeHeaders header = new MimeHeaders();
        header.addHeader("Content-Type", "application/soap+xml");

        MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

        SOAPMessage message;
        message = factory.createMessage(header, new ByteArrayInputStream(xmlNfedados.getBytes()));
        SOAPConnection con = SOAPConnectionFactory.newInstance().createConnection();
        res = con.call(message, url);

        con.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

在此连接之前,我们在jvm中设置了这个属性:

public void setPropertiesA1(String caminhoCertificado, String senhaCertificado, String caminhoCacerts){
    //preparar as propriedades
    Properties properties = System.getProperties();
    properties.setProperty("java.protocol.handler.pkgs",  "com.sun.net.ssl.internal.www.protocol");
    properties.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
    properties.setProperty("javax.net.ssl.keyStore", caminhoCertificado);
    properties.setProperty("javax.net.ssl.keyStorePassword", senhaCertificado);
    properties.setProperty("javax.net.ssl.trustStoreType", "JKS");
    properties.setProperty("javax.net.ssl.trustStore", caminhoCacerts);
    properties.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    properties.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
    //properties.setProperty("javax.net.debug", "all");

}

一切都很好。直到我们需要发送和接收供应商的电子邮件。在收到电子邮件的情况下,我们使用以下内容:

public static Store conectar(String login, String senha)
throws NoSuchProviderException, MessagingException
{
    logger.info("Conectando ao servidor de e-mail");

    logger.info("--------------Processo de leitura iniciado-----------------");
    String imap = "imaps";
    String host = "pop.gmail.com";
    int porta = 587;
    String diretorioServidor = "Inbox";

    Properties prop = new Properties();
    //System.out.println("numero antes " + System.getProperties().size());
    Session session = Session.getInstance(prop);

    //URLName url = new URLName(imap, host, porta, diretorioServidor, login, senha);

    Store store = session.getStore("pop3s");

    store.connect(host, login, senha);
    //System.out.println("numero depois " + System.getProperties().size());
    logger.info("Conexão estabelecida com servidor IMAP.");
    return store;
}
conectar 方法返回的 store 对象由以下内容处理:

public static Folder recuperarCaixaEntrada(Store store)
throws MessagingException
{
    Folder folder = store.getFolder("Inbox");
    folder.open(2);

    return folder;
}

对象文件夹中包含的消息稍后将在proccessMail()方法中处理:

public FileInputStream processMail()
throws MessagingException
{
    FileInputStream anexo = null;
    try
    {
      logger.info("Quantida de de e-mails encontrados na caixa de entrada: " + this.messages.length);

     if (this.messages.length <= 0) {
        this.folder.close(true);

        this.store.close();

        System.out.println("esta conectado " + store.isConnected());
        return null;
     }

     System.out.println("Existem na caixa de entrada: " + this.messages.length + " para serem tratados!");

     System.out.println("Tratando e-mail:1 de " + this.messages.length);
     logger.info("Tratando e-mail:1 de " + this.messages.length);

     this.message = this.messages[0];
     System.out.println("Content Type: " + this.message.getContentType());

     if (!this.message.getContentType().equals("text/plain; charset=br-ascii"))
     {
       anexo = getEmail(0);
       System.out.println("Baixou anexo");
     } else {
       System.out.println("Não baixou anexo");
     }

     this.folder.close(true);

     this.store.close();
     } catch (AuthenticationFailedException e) {
       this.store.close();
       logger.error("Falha na Autentica&#65533;&#65533;o: " + e.getMessage());
     } catch (FolderClosedException e) {
       this.store.close();
       logger.error("Falha no fechamento da pasta: " + e.getMessage());
     } catch (FolderNotFoundException e) {
       this.store.close();
       logger.error("Pasta n&#65533;o encontrada: " + e.getMessage());
     } catch (NoSuchProviderException e) {
       this.store.close();
       logger.error("NoSuchProviderException: " + e.getMessage());
     } catch (ReadOnlyFolderException e) {
       this.store.close();
       logger.error("Pasta com permiss&#65533;o de somente leitura: " + e.getMessage());
     } catch (StoreClosedException e) {
       this.store.close();
       logger.error("Erro ao fechar pasta auxiliar: " + e.getMessage());
     } catch (Exception e) {
       this.store.close();
       logger.error("Erro no m&#65533;todo Principal: " + e.getMessage());
       System.out.println(e.getMessage());
    }
  return anexo;
}

因此,在实施接收电子邮件的过程之后,税务文件的发送开始返回以下错误:

com.sun.xml.messaging.saaj.SOAPExceptionImpl: java.security.PrivilegedActionException: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
17:37:56,434 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at      com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConn     ection.java:191)
17:37:56,435 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at     br.com.nfe.business.ComunicacaoReceitaBusiness.conecta(ComunicacaoReceitaB    usiness.java:205)
17:37:56,436 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.nfe.business.ComunicacaoReceitaBusiness.criaConexao(ComunicacaoReceitaBusiness.java:39)
17:37:56,436 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.nfe.business.EmissaoReceitaBusiness.emissaoNfe(EmissaoReceitaBusiness.java:46)
17:37:56,437 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.coliseu.nfe.business.NfeBusiness.emitirNota(NfeBusiness.java:1739)
17:37:56,437 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.coliseu.controller.NotaSaidaController.emitir(NotaSaidaController.java:1023)
17:37:56,438 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
17:37:56,439 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
17:37:56,439 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
17:37:56,440 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at java.lang.reflect.Method.invoke(Method.java:606)
17:37:56,440 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.interceptor.ExecuteMethodInterceptor.intercept(ExecuteMethodInterceptor.java:61)
17:37:56,441 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
17:37:56,441 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,442 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
17:37:56,443 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,443 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:61)
17:37:56,444 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,444 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.coliseu.interceptor.LoginInterceptor.intercept(LoginInterceptor.java:92)
17:37:56,445 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
17:37:56,446 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,446 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
17:37:56,447 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,447 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor.intercept(ExceptionHandlerInterceptor.java:71)
17:37:56,448 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
17:37:56,448 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,449 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.interceptor.FlashInterceptor.intercept(FlashInterceptor.java:83)
17:37:56,450 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
17:37:56,450 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,451 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor.intercept(ParametersInstantiatorInterceptor.java:93)
17:37:56,451 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
17:37:56,452 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,452 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.interceptor.InstantiateInterceptor.intercept(InstantiateInterceptor.java:48)
17:37:56,453 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
17:37:56,454 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,454 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.interceptor.ResourceLookupInterceptor.intercept(ResourceLookupInterceptor.java:69)
17:37:56,455 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
17:37:56,455 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,456 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
17:37:56,457 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
17:37:56,457 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.core.EnhancedRequestExecution.execute(EnhancedRequestExecution.java:44)
17:37:56,458 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.VRaptor$1.insideRequest(VRaptor.java:91)
17:37:56,458 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at     br.com.caelum.vraptor.ioc.spring.SpringProvider.provideForRequest(SpringProvider.java:58)
17:37:56,459 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:88)
17:37:56,459 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280)
17:37:56,460 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
17:37:56,460 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
17:37:56,461 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
17:37:56,462 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280)
17:37:56,462 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
17:37:56,463 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
17:37:56,463 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
17:37:56,464 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)
17:37:56,464 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
17:37:56,465 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
17:37:56,465 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
17:37:56,466 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
17:37:56,467 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
17:37:56,467 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
17:37:56,468 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
17:37:56,468 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
17:37:56,469 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at java.lang.Thread.run(Thread.java:745)
17:37:56,470 ERROR [stderr] (http-localhost-127.0.0.1-8080-6) Caused by: java.security.PrivilegedActionException: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
17:37:56,470 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at java.security.AccessController.doPrivileged(Native Method)
17:37:56,471 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:185)
17:37:56,471 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   ... 60 more
17:37:56,472 ERROR [stderr] (http-localhost-127.0.0.1-8080-6) Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
17:37:56,472 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:389)
17:37:56,473 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection$PriviledgedPost.run(HttpSOAPConnection.java:214)
17:37:56,474 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   ... 62 more
17:37:56,474 ERROR [stderr] (http-localhost-127.0.0.1-8080-6) Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
17:37:56,475 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
17:37:56,476 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)
17:37:56,476 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
17:37:56,477 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
17:37:56,477 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1446)
17:37:56,478 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
17:37:56,478 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.Handshaker.processLoop(Handshaker.java:913)
17:37:56,479 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.Handshaker.process_record(Handshaker.java:849)
17:37:56,479 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023)
17:37:56,480 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
17:37:56,480 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
17:37:56,481 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
17:37:56,481 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
17:37:56,482 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
17:37:56,483 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1092)
17:37:56,483 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
17:37:56,484 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:346)
17:37:56,485 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   ... 63 more
17:37:56,485 ERROR [stderr] (http-localhost-127.0.0.1-8080-6) Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
17:37:56,486 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
17:37:56,487 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
17:37:56,488 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.validator.Validator.validate(Validator.java:260)
17:37:56,488 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
17:37:56,489 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
17:37:56,489 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
17:37:56,490 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1428)
17:37:56,490 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   ... 75 more
17:37:56,491 ERROR [stderr] (http-localhost-127.0.0.1-8080-6) Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
17:37:56,492 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
17:37:56,492 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
17:37:56,493 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    17:37:56,493 ERROR [stderr] (http-localhost-127.0.0.1-8080-6)   ... 81 more

因此,错误消息是明确的:无法找到所请求目标的有效证书路径 出于某种原因,我们的应用程序找不到证书路径。但是,如前所述,每次需要发送文档时都会调用 setPropertiesA1()方法。除此之外,我已经检查过,在应用程序尝试发送文档之前,证书路径是否正常,确实如此。属性“javax.net.ssl.keyStore”具有正确的值。

如果有人对这种类型的联系如何运作有深刻的理解,可以让我们一瞥解决方案,或指出我们做错了什么,我们将非常感激。

我希望这个问题足够清楚。

我们使用JBoss AS 7.1.1.Final作为服务器应用程序。

更新 这里的问题不仅仅是“缺少证书”,因为如果我们评论负责发送电子邮件的代码,它也不会起作用。

另一个澄清点是,两个连接都没有同时完成,它们一个接一个地发生。更准确地说,在连接税务文件部分之前连接电子邮件部分。

这里的主要问题是: 在我们发送或接收电子邮件之后,为什么SOAPConnection没有从属性获取路径?

2 个答案:

答案 0 :(得分:0)

为了在安全的http连接(https)上创建连接,您需要将后端服务的客户端证书导入到您的java密钥库文件(jks)中,该文件将用于加密您通过其发送的消息电线,只能使用后端私钥解密。因此,在错误中,您不会在本地Java密钥库文件中拥有该客户端证书。将其导入您的本地jks文件,它将工作。

可以使用以下命令将客户端证书导入Java密钥库。 Here是它的java文档。

keytool -import -alias susan -file Example.cer -keystore exampleraystore.jks

如果您没有证书,可以按照以下命令导出客户端证书。 Here是它的java文档。

keytool -export -keystore examplestore -alias signFiles -file Example.cer

<强> [UPDATE] 我的上述声明是有效的,如果它抱怨丢失证书。但在你的情况下,在openJDK中它是bug,您可能需要获取openJDK的最新修订版本或移至OracleJDK。

答案 1 :(得分:0)

经过对此事的广泛研究后,我找到了解决方案,即与sslcontext一起实现keymanager和trustmanager。这将在HttpsConnection对象中使用。

方法&#34; SOAPMessage conecta(String xmlNfedados,URL url)&#34;被重构:

public String conecta(String xmlNfedados, URL url) throws SOAPException{
    String outputString = "";
    try {
        if(context != null){

            URLConnection connection = url.openConnection();
            HttpsURLConnection httpsconn = (HttpsURLConnection) connection;

            httpsconn.setSSLSocketFactory(this.context.getSocketFactory());

            byte[] buffer = new byte[xmlNfedados.length()];
            buffer = xmlNfedados.getBytes();

            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            bout.write(buffer);

            byte[] b = bout.toByteArray();

            httpsconn.setRequestProperty("Content-Type", "application/soap+xml");
            httpsconn.setRequestMethod("POST");

            httpsconn.setDoOutput(true);
            httpsconn.setDoInput(true);

            OutputStream out = httpsconn.getOutputStream();

            out.write(b);
            out.close();

            InputStreamReader isr = new InputStreamReader(httpsconn.getInputStream());

            BufferedReader in = new BufferedReader(isr);

            String responseString = "";

            while((responseString = in.readLine()) != null){
                outputString = outputString + responseString;
            }

            /*MimeHeaders header = new MimeHeaders();
            header.addHeader("Content-Type", "application/soap+xml");

            MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

            SOAPMessage message;
            message = factory.createMessage(header, new ByteArrayInputStream(xmlNfedados.getBytes()));
            SOAPConnection con = SOAPConnectionFactory.newInstance().createConnection();
            res = con.call(message, url);*/

        } else {
            throw new IllegalStateException("SSContext não inicializado");
        }

        //con.close();
    } catch (IOException e) {
        e.printStackTrace();
    } 
    return outputString;
}

方法&#34; getsslContext&#34;负责初始化sslContext:

@Override
public SSLContext getSslContext(String camingoCert, String caminhoCacerts, String senhaCertificado){
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
        KeyManager[] km = getKeyManager(camingoCert, senhaCertificado);
        TrustManager[] tm = getTrustManager(caminhoCacerts);

        sc.init(km, tm, null);

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return sc;
}

以下是&#34; getKeyManager&#34;:     private KeyManager [] getKeyManager(String caminhoCert,String senha){         KeyManagerFactory kmf = null;

    try {
        kmf = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );
        KeyStore ks = KeyStore.getInstance( "pkcs12" );
        ks.load(new FileInputStream( caminhoCert ), senha.toCharArray() );

        kmf.init( ks, senha.toCharArray() );

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    }
    return kmf.getKeyManagers();
}

和&#34; getTrustManager&#34;:

private TrustManager[] getTrustManager(String caminhoCacerts){
    TrustManagerFactory tmf = null;
    try {

        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(new FileInputStream(caminhoCacerts), SENHACACERTS.toCharArray());
        tmf.init(ts);

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return tmf.getTrustManagers();
}