Erro ao enviar XML por WebService

Boa a tarde a todos,

Prezados,

Estou desenvolvendo um sistema de Nota Fiscal Eletronica - NFe, estou efetuando a parte de consulta de CNPJ para retornar a Inscrição Municipal. O XML esta sendo gerado corretamente, e validado de acordo com o esquema passado pela prefeitura, porem na hora de enviar os dados via web service aparece o seguinte erro :

Obs: Este erro e problema com o path, porem ja mudei os arquivos de diretorio, porem nao houve sucesso, continua com o mesmo erro, sendo assim alguem poderia ajudar ?

org.apache.axis2.AxisFault: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:83)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:84)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:346)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:542)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:189)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:364)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:208)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:448)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:401)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:228)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)
at br.gov.sp.prefeitura.www.nfe.LoteNFeStub.ConsultaCNPJ(LoteNFeStub.java:526)
at br.com.cienci.nfe.enquiry.WebServiceEnquiry.enquiryCnpj(WebServiceEnquiry.java:89)
at br.com.cienci.ws.ConsultaCnpjWs.getConsultaWS(ConsultaCnpjWs.java:68)
at br.com.cienci.nfe.parser.Teste.main(Teste.java:56)
Caused by: com.ctc.wstx.exc.WstxIOException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:313)
at org.apache.axiom.om.impl.MTOMXMLStreamWriter.flush(MTOMXMLStreamWriter.java:146)
at org.apache.axis2.databinding.utils.writer.MTOMAwareXMLSerializer.flush(MTOMAwareXMLSerializer.java:79)
at org.apache.axis2.databinding.ADBDataSource.serialize(ADBDataSource.java:94)
at org.apache.axiom.om.impl.llom.OMSourcedElementImpl.internalSerializeAndConsume(OMSourcedElementImpl.java:664)
at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:918)
at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerializeAndConsume(OMElementImpl.java:947)
at org.apache.axiom.soap.impl.llom.SOAPEnvelopeImpl.serializeInternally(SOAPEnvelopeImpl.java:240)
at org.apache.axiom.soap.impl.llom.SOAPEnvelopeImpl.internalSerialize(SOAPEnvelopeImpl.java:228)
at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerializeAndConsume(OMElementImpl.java:947)
at org.apache.axiom.om.impl.llom.OMNodeImpl.serializeAndConsume(OMNodeImpl.java:471)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:79)
… 21 more
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
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1591)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:975)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:123)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1096)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:623)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:104)
at org.apache.commons.httpclient.ChunkedOutputStream.flushCacheWithAppend(ChunkedOutputStream.java:121)
at org.apache.commons.httpclient.ChunkedOutputStream.write(ChunkedOutputStream.java:179)
at com.ctc.wstx.io.UTF8Writer.flush(UTF8Writer.java:96)
at com.ctc.wstx.sw.BufferingXmlWriter.flush(BufferingXmlWriter.java:214)
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:311)
… 32 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:285)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:191)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:954)
… 46 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
Error in Enquiry!!
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:280)
… 52 more

Segue abaixo o codigo da classe responsavel pelo envio do codigo;

package br.com.cienci.nfe.enquiry;

import br.com.cienci.nfe.parser.NfeUtil;
import br.gov.sp.prefeitura.www.nfe.LoteNFeStub;
import br.gov.sp.prefeitura.www.nfe.LoteNFeStub.CancelamentoNFeRequest;
import br.gov.sp.prefeitura.www.nfe.LoteNFeStub.CancelamentoNFeResponse;
import br.gov.sp.prefeitura.www.nfe.LoteNFeStub.ConsultaCNPJRequest;
import br.gov.sp.prefeitura.www.nfe.LoteNFeStub.ConsultaCNPJResponse;
import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.Security;
import javax.swing.JOptionPane;
import org.apache.axis2.AxisFault;

/**
 * WebServiceEnquiry.java
 * Criado em 16/10/2008
 * @author Ciro S. Santos
 * @version 1.0
 *
 * Classe que consome o Web Service de consulta CNPJ da prefeitura de SP.
 */
public class WebServiceEnquiry {

    /**
     * Chave privada para a conexão segura com HTTPS
     */
    private String privateKey;
    
    /**
     * Senha da chave privada para a conexão segura com HTTPS
     */
    private String passPrivateKey;
    
    /**
     * Chave publica para a conexão segura com HTTPS
     */
    private String jks;
    
    /**
     * Senha da chave publica para a conexão segura com HTTPS
     */
    private String passJks;

    /**
     * Retorna uma String no formato XML com a resposta da consulta do web service.
     * Esse método faz o consumo do web service.
     * 
     * @param xml
     * @param privateKey
     * @param passPrivateKey
     * @param jks
     * @param passJks
     * @return String
     */
    public String enquiryCnpj(String xml, String privateKey, String passPrivateKey,String jks, String passJks) {
             
        String result = "";
        File file1 = new File("C:\\teste\\teste");
     
         String pathJks = file1+"\\"+ jks; // esse e o nome do arquivo com a extenção JKS
         String pathPrivate = file1+"\\"+privateKey;// esse e o nome do arquivo do certificado digital.
               
        this.privateKey = pathPrivate;        
        this.jks = pathJks;
        this.passPrivateKey = passPrivateKey;
        this.passJks = passJks;
        
        if (this.setSecurityProperties()) {

            ConsultaCNPJRequest consultaCNPJRequest = null;
            ConsultaCNPJResponse consultaCNPJResponse = null;
            LoteNFeStub stub = null;

            try {
                consultaCNPJRequest = new ConsultaCNPJRequest();
                consultaCNPJRequest.setVersaoSchema(1);
                consultaCNPJRequest.setMensagemXML(xml);
                
                stub = new LoteNFeStub();
                consultaCNPJResponse = stub.ConsultaCNPJ(consultaCNPJRequest);
                result = consultaCNPJResponse.getRetornoXML();
                
            } catch (AxisFault ex) {
                ex.printStackTrace();
                return null;
            } catch (RemoteException ex) {
                ex.printStackTrace();
                return null;
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        } else {
            System.out.println("Problems in set security properties");
            return null;
        }

        return result;
    }
    
   /* 
    public String enquirySolicitacaoCancelamento(String xml, String privateKey, String passPrivateKey,String jks, String passJks){
        
        String result = "";
        
        File file1 = new File("src\\securityResources");
        String pathPrivate = file1.getAbsolutePath() + "\\" + privateKey;
        String pathJks = file1.getAbsolutePath() + "\\" + jks;        
        this.privateKey = NfeUtil.generatePathToSecurity(pathPrivate);        
        this.jks = NfeUtil.generatePathToSecurityJks(pathJks);        
        this.passPrivateKey = passPrivateKey;
        this.passJks = passJks;
        
        if (this.setSecurityProperties()) {


            CancelamentoNFeRequest cancelmentoNFErequest = null;
            CancelamentoNFeResponse cancelamentoNFEresponse = null;
            LoteNFeStub stub = null;

            try {
                cancelmentoNFErequest = new CancelamentoNFeRequest();
                cancelmentoNFErequest.setVersaoSchema(1);
                cancelmentoNFErequest.setMensagemXML(xml);

                stub = new LoteNFeStub();
                cancelamentoNFEresponse = stub.CancelamentoNFe(cancelmentoNFErequest);
                result = cancelamentoNFEresponse.getRetornoXML();

            } catch (AxisFault ex) {
                ex.printStackTrace();
                return null;
            } catch (RemoteException ex) {
                ex.printStackTrace();
                return null;
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        } 
        
        return "";
    }
    /**
     * Retorna true se o proxy para uma conexão segura foi configurado corretamente e false
     * se ocorrer algum tipo de erro.
     * 
     * @return boolean
     */
    private boolean setSecurityProperties() {

        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
            System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
            System.setProperty("javax.net.ssl.keyStore", this.privateKey);
            System.setProperty("javax.net.ssl.keyStorePassword", this.passPrivateKey);
            System.setProperty("javax.net.ssl.trustStoreType", "JKS");
            System.setProperty("javax.net.ssl.trustStore", this.jks);
            System.setProperty("javax.net.ssl.trustStorePassword", this.passJks);

        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }    
}

Cara estou comecando agora a implementar a nfe, e estou com um problema parecido quando vou verificar o status de outro estado que for SP, me retorna um erro parecido com esse seu.

Agora deixa eu te fazer umas perguntas, rsrsrs

Vc importou os WSDL dos estados??
vc esta fazendo a conexão com webservice como??

se puder me responder eu agradeço

Aparentemente parece erro de Certificado Digital, nao sei ao certo, tem um post com passa a passo bem didatico aqui no guj, http://www.guj.com.br/posts/list/15/52035.java

Segue a resposta do que perguntou Marcelo:

Estou fazendo a conexao por proxy, essa classe que posti e o codigo que fiz para conectar com o server da prefeitura.

Estou utilizando as bibliotecas Axis2

Se observar, existe 2 declarações de uma variavel consultaCNPJRequest e consultaCNPJResponse, as classes ConsultaCNPJRequest e ConsultaCNPJRequest
foram geradas atraves do Eclipse, nao sei se vc sabe, o eclipse conecta com o server e gera o codigo Java com todos os metodos necessarios…

Atraves das variaveis consultaCNPJRequest e possivel enviar o arquivo xml ou melhor uma String com todo codigo XML, e vc vai receber a resposta q tambem e uma String com todas as tags XML.

Obs. Não cheguei a utilizar nada dos outros estados.

Obs 2: abre um topico com a sua duvida, para que outros possa responder… qualquer coisa volte a postar… segue o meu msn: elton_csantana@hotmail.com.

Você está usando o Axis.

Você tem que implementar a Autenticação mutua usando o HttpClient da apache.

http://hc.apache.org/httpclient-3.x/

Pelo menos foi assim que eu consegui.

[]s

galera primeiramente obrigado pelas respostas e presteza…

Cristiano vou tentar fazer este processo, qq coisa volto a postar.

Luciano esse post acho que e possivel ajudar… vou testar tbem… assim q obter uma resposta volto a postar.

grato desde já EltoN C.

Bom estou no desenvolvimento de NF-e e web services a algum tempo, talvez possa te ajudar.
Esse erro é dado quando ele nao encontra o certificado digital. De uma olhada direito no caminho certifique-se que o jks está lá.

[ ]s,

Mateus obrigado pela ajuda…

Em resposta a sua pergunta, ja verifiquei e os arquivos se encontram no diretorio especificado, ate mudei o diretorio, para a unidade c:/ para tentar rodar, mas não houve sucesso…

Sendo assim questiono se e necessario incluir mais algum codigo, para reconhecer o caminho do arquivo ?

segue o metodo responsavel.

public String enquiryCnpj(String xml, String privateKey, String passPrivateKey,String jks, String passJks) {
             
        String result = "";
        File file1 = new File("C:\\teste\\teste");
         String pathJks = file1+"\\"+ jks;// essa variavel recebe o caminho e o nome do arquivo jks
        String pathPrivate = file1+"\\"+privateKey; //essa variavel recebe o caminho e o nome do arquivo com a chave privada (Certificado Digital)
              
        this.privateKey = pathPrivate;        
        this.jks = pathJks;
        this.passPrivateKey = passPrivateKey;
        this.passJks = passJks;
        
        if (this.setSecurityProperties()) {

            ConsultaCNPJRequest consultaCNPJRequest = null;
            ConsultaCNPJResponse consultaCNPJResponse = null;
            LoteNFeStub stub = null;

            try {
                consultaCNPJRequest = new ConsultaCNPJRequest();
                consultaCNPJRequest.setVersaoSchema(1);
                consultaCNPJRequest.setMensagemXML(xml);
                
                stub = new LoteNFeStub();
                consultaCNPJResponse = stub.ConsultaCNPJ(consultaCNPJRequest);
                result = consultaCNPJResponse.getRetornoXML();
                
            } catch (AxisFault ex) {
                ex.printStackTrace();
                return null;
            } catch (RemoteException ex) {
                ex.printStackTrace();
                return null;
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        } else {
            System.out.println("Problems in set security properties");
            return null;
        }

        return result;
    }

Elton,

O JKS ele está encontrando, só que não comunicação com o WS do Sefaz é via SSL com autenticação mutua, então voce tem que estabelecer uma conexao SSL.

Por isso ta dando o erro.

[]s

Usando o HttpClient da apache ficou assim:


        Protocol authhttps = new Protocol("https",
                new AuthSSLProtocolSocketFactory(caminhoJKS,senhaCertificado), 443);
        Protocol.registerProtocol("https", authhttps);

        HttpClient httpClient = new HttpClient();

        Options options = new Options();

        options.setTransportInProtocol(Constants.TRANSPORT_HTTPS);
        options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);

Classe AuthSSLProtocolSocketFactory (Adaptada)

/*
 * $HeadURL$
 * $Revision$
 * $Date$
 *
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package integracao.sefaz;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * <p>
 * AuthSSLProtocolSocketFactory can be used to validate the identity of the HTTPS 
 * server against a list of trusted certificates and to authenticate to the HTTPS 
 * server using a private key. 
 * </p>
 * 
 * <p>
 * AuthSSLProtocolSocketFactory will enable server authentication when supplied with
 * a {@link KeyStore truststore} file containg one or several trusted certificates. 
 * The client secure socket will reject the connection during the SSL session handshake 
 * if the target HTTPS server attempts to authenticate itself with a non-trusted 
 * certificate.
 * </p>
 * 
 * <p>
 * Use JDK keytool utility to import a trusted certificate and generate a truststore file:    
 *    <pre>
 *     keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
 *    </pre>
 * </p>
 * 
 * <p>
 * AuthSSLProtocolSocketFactory will enable client authentication when supplied with
 * a {@link KeyStore keystore} file containg a private key/public certificate pair. 
 * The client secure socket will use the private key to authenticate itself to the target 
 * HTTPS server during the SSL session handshake if requested to do so by the server. 
 * The target HTTPS server will in its turn verify the certificate presented by the client
 * in order to establish client's authenticity
 * </p>
 * 
 * <p>
 * Use the following sequence of actions to generate a keystore file
 * </p>
 *   <ul>
 *     <li>
 *      <p>
 *      Use JDK keytool utility to generate a new key
 *      <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre>
 *      For simplicity use the same password for the key as that of the keystore
 *      </p>
 *     </li>
 *     <li>
 *      <p>
 *      Issue a certificate signing request (CSR)
 *      <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre>
 *     </p>
 *     </li>
 *     <li>
 *      <p>
 *      Send the certificate request to the trusted Certificate Authority for signature. 
 *      One may choose to act as her own CA and sign the certificate request using a PKI 
 *      tool, such as OpenSSL.
 *      </p>
 *     </li>
 *     <li>
 *      <p>
 *       Import the trusted CA root certificate
 *       <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre> 
 *      </p>
 *     </li>
 *     <li>
 *      <p>
 *       Import the PKCS#7 file containg the complete certificate chain
 *       <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre> 
 *      </p>
 *     </li>
 *     <li>
 *      <p>
 *       Verify the content the resultant keystore file
 *       <pre>keytool -list -v -keystore my.keystore</pre> 
 *      </p>
 *     </li>
 *   </ul>
 * <p>
 * Example of using custom protocol socket factory for a specific host:
 *     <pre>
 *     Protocol authhttps = new Protocol("https",  
 *          new AuthSSLProtocolSocketFactory(
 *              new URL("file:my.keystore"), "mypassword",
 *              new URL("file:my.truststore"), "mypassword"), 443); 
 *
 *     HttpClient client = new HttpClient();
 *     client.getHostConfiguration().setHost("localhost", 443, authhttps);
 *     // use relative url only
 *     GetMethod httpget = new GetMethod("/");
 *     client.executeMethod(httpget);
 *     </pre>
 * </p>
 * <p>
 * Example of using custom protocol socket factory per default instead of the standard one:
 *     <pre>
 *     Protocol authhttps = new Protocol("https",  
 *          new AuthSSLProtocolSocketFactory(
 *              new URL("file:my.keystore"), "mypassword",
 *              new URL("file:my.truststore"), "mypassword"), 443); 
 *     Protocol.registerProtocol("https", authhttps);
 *
 *     HttpClient client = new HttpClient();
 *     GetMethod httpget = new GetMethod("https://localhost/");
 *     client.executeMethod(httpget);
 *     </pre>
 * </p>
 * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
 * 
 * <p>
 * DISCLAIMER: HttpClient developers DO NOT actively support this component.
 * The component is provided as a reference material, which may be inappropriate
 * for use without additional customization.
 * </p>
 */
public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory {

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class);
    private String keyStoreDir = null;
    private String keyStorePassword = null;
    private SSLContext sslcontext = null;

    /**
     * Constructor for AuthSSLProtocolSocketFactory. Either a keystore or truststore file
     * must be given. Otherwise SSL context initialization error will result.
     * 
     * @param keystoreUrl URL of the keystore file. May be <tt>null</tt> if HTTPS client
     *        authentication is not to be used.
     * @param keystorePassword Password to unlock the keystore. IMPORTANT: this implementation
     *        assumes that the same password is used to protect the key and the keystore itself.
     * @param truststoreUrl URL of the truststore file. May be <tt>null</tt> if HTTPS server
     *        authentication is not to be used.
     * @param truststorePassword Password to unlock the truststore.
     */
    public AuthSSLProtocolSocketFactory(
            final String keyStoreDir, final String keyStorePassword) {
        super();
        this.keyStoreDir = keyStoreDir;
        this.keyStorePassword = keyStorePassword;
    }

    private static KeyStore createKeyStore(final String keyStoreDir, final String password)
            throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
        if (keyStoreDir == null) {
            throw new IllegalArgumentException("Keystore url may not be null");
        }
        LOG.debug("Initializing key store");
        KeyStore keystore = KeyStore.getInstance("jks");
        InputStream is = null;
        try {
            is = new FileInputStream(new File(keyStoreDir));
            keystore.load(is, password != null ? password.toCharArray() : null);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return keystore;
    }

    private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
            throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
        if (keystore == null) {
            throw new IllegalArgumentException("Keystore may not be null");
        }
        LOG.debug("Initializing key manager");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, password != null ? password.toCharArray() : null);
        return kmfactory.getKeyManagers();
    }

    private SSLContext createSSLContext() {
        try {
            KeyManager[] keymanagers = null;
            TrustManager[] trustmanagers = null;
            if (this.keyStoreDir != null) {
                KeyStore keystore = createKeyStore(this.keyStoreDir, this.keyStorePassword);
                if (LOG.isDebugEnabled()) {
                    Enumeration aliases = keystore.aliases();
                    while (aliases.hasMoreElements()) {
                        String alias = (String) aliases.nextElement();
                        Certificate[] certs = keystore.getCertificateChain(alias);
                        if (certs != null) {
                            LOG.debug("Certificate chain '" + alias + "':");
                            for (int c = 0; c < certs.length; c++) {
                                if (certs[c] instanceof X509Certificate) {
                                    X509Certificate cert = (X509Certificate) certs[c];
                                    LOG.debug(" Certificate " + (c + 1) + ":");
                                    LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                    LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                    LOG.debug("  Valid from: " + cert.getNotBefore());
                                    LOG.debug("  Valid until: " + cert.getNotAfter());
                                    LOG.debug("  Issuer: " + cert.getIssuerDN());
                                }
                            }
                        }
                    }
                }
                keymanagers = createKeyManagers(keystore, this.keyStorePassword);
            }

            trustmanagers = new TrustManager[]{new X509TrustManager() {

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }

                    @Override
                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs,
                            String authType) {
                        for (int c = 0; c < certs.length; c++) {
                            X509Certificate cert = certs[c];
                            System.out.println(" Client certificate " + (c + 1) + ":");
                            System.out.println("  Subject DN: " + cert.getSubjectDN());
                            System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                            System.out.println("  Valid from: " + cert.getNotBefore());
                            System.out.println("  Valid until: " + cert.getNotAfter());
                            System.out.println("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
                    };

            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(keymanagers, trustmanagers, null);
            return sslcontext;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        return null;
    }

    private SSLContext getSSLContext() {
        if (this.sslcontext == null) {
            this.sslcontext = createSSLContext();
        }
        return this.sslcontext;
    }

    /**
     * Attempts to get a new socket connection to the given host within the given time limit.
     * <p>
     * To circumvent the limitations of older JREs that do not support connect timeout a 
     * controller thread is executed. The controller thread attempts to create a new socket 
     * within the given limit of time. If socket constructor does not return until the 
     * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
     * </p>
     *  
     * @param host the host name/IP
     * @param port the port on the host
     * @param clientHost the local host name/IP to bind the socket to
     * @param clientPort the port on the local machine
     * @param params {@link HttpConnectionParams Http connection parameters}
     * 
     * @return Socket a new socket
     * 
     * @throws IOException if an I/O error occurs while creating the socket
     * @throws UnknownHostException if the IP address of the host cannot be
     * determined
     */
    @Override
    public Socket createSocket(
            final String host,
            final int port,
            final InetAddress localAddress,
            final int localPort,
            final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        SocketFactory socketfactory = getSSLContext().getSocketFactory();
        if (timeout == 0) {
            return socketfactory.createSocket(host, port, localAddress, localPort);
        } else {
            Socket socket = socketfactory.createSocket();
            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            SocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
            return socket;
        }
    }

    /**
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
     */
    @Override
    public Socket createSocket(
            String host,
            int port,
            InetAddress clientHost,
            int clientPort)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                host,
                port,
                clientHost,
                clientPort);
    }

    /**
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
     */
    @Override
    public Socket createSocket(String host, int port)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                host,
                port);
    }

    /**
     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
     */
    @Override
    public Socket createSocket(
            Socket socket,
            String host,
            int port,
            boolean autoClose)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                socket,
                host,
                port,
                autoClose);
    }
}

Faça isso antes de chamar o WS.

Então Cristiano, esse processo esta feito, ele esta se conectando com o server, porem na hora da validação ele aparece este erro… Ele nao encontra o arquivo especificado…

Agora eu não sei o que estou fazendo de errado, para nao encontrar os arquivos… seria possivel ajudar ? nao sei se precisa especificar algo antes…

Estou com exatamente esse problema ao conectar na prefeitura da cidade de são paulo, por favor, se alguém conseguiu resolver, me informe como!

Obrigado!