Cliente WebService via Ksoap e Autenticação

0 respostas
S

Galera pesquisando na net, vi que teve alguns que conseguiram usar o ksoap para se conectar com webservices que exige autenticação, bom o que eu fiz foi baixar os fontes do ksoap2 para j2se, e fazer a mudança na classe transpote no metodo call();

Ficou desta forma

package testeconexao;

import java.io.*;

import org.ksoap2.*;
import org.ksoap2.transport.ServiceConnection;
import org.ksoap2.transport.ServiceConnectionSE;
import org.ksoap2.transport.Transport;
import org.xmlpull.v1.*;

/**
 * A J2SE based HttpTransport layer.
 */
public class httpTransport22 extends Transport {

    /**
     * Creates instance of HttpTransportSE with set url
     *
     * @param url
     *            the destination to POST SOAP data
     */
    public httpTransport22(String url) {
        super(url);
    }

    /**
     * set the desired soapAction header field
     *
     * @param soapAction
     *            the desired soapAction
     * @param envelope
     *            the envelope containing the information for the soap call.
     */
    public void call(String soapAction, SoapEnvelope envelope, String Login, String senha) throws IOException, XmlPullParserException {
        if (soapAction == null) {
            soapAction = "\"\"";
        }
        byte[] requestData = createRequestData(envelope);
        requestDump = debug ? new String(requestData) : null;
        responseDump = null;
        ServiceConnection connection = getServiceConnection();
        if (Login != null && senha != null) {
            StringBuffer buf = new StringBuffer(Login);
            buf.append(':').append(senha);
            byte[] raw = buf.toString().getBytes();
            buf.setLength(0);
            buf.append("Basic ");
            org.kobjects.base64.Base64.encode(raw, 0, raw.length, buf);
            connection.setRequestProperty("Authorization", buf.toString());
        }
        connection.setRequestProperty("User-Agent", "kSOAP/2.0");
        connection.setRequestProperty("SOAPAction", soapAction);
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestProperty("Connection", "close");
        connection.setRequestProperty("Content-Length", "" + requestData.length);
        connection.setRequestMethod("POST");
        connection.connect();
        OutputStream os = connection.openOutputStream();
        os.write(requestData, 0, requestData.length);
        os.flush();
        os.close();
        requestData = null;
        InputStream is;
        try {
            //connection.connect();
            is = connection.openInputStream();
        } catch (IOException e) {
            is = connection.getErrorStream();
            if (is == null) {
                connection.disconnect();
                throw (e);
            }
            System.out.println(e.getMessage());
        }
        if (debug) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[256];
            while (true) {
                int rd = is.read(buf, 0, 256);
                if (rd == -1) {
                    break;
                }
                bos.write(buf, 0, rd);
            }
            bos.flush();
            buf = bos.toByteArray();
            responseDump = new String(buf);
            is.close();
            is = new ByteArrayInputStream(buf);
        }
        parseResponse(envelope, is);
    }

    protected ServiceConnection getServiceConnection() throws IOException {
        return new ServiceConnectionSE(url);
    }

    @Override
    public void call(String arg0, SoapEnvelope arg1) throws IOException, XmlPullParserException {
        call(arg0, arg1, null, null);
    }
}

Foi adicionado a este método o login e senha a ser autenticado quando for executar conexão e adicionei as seguintes linhas para que este login entre no cabeçalho da conexao.

if (Login != null && senha != null) {
            StringBuffer buf = new StringBuffer(Login);
            buf.append(':').append(senha);
            byte[] raw = buf.toString().getBytes();
            buf.setLength(0);
            buf.append("Basic ");
            org.kobjects.base64.Base64.encode(raw, 0, raw.length, buf);
            connection.setRequestProperty("Authorization", buf.toString());
        }

mas mesmo com tudo isso quando tento me conectar o erro de que a conexã foi recusada por nao estar validade desapareceu mas deu lugar a este erro.

20/03/2009 10:10:42 testeconexao.Main main
SEVERE: null
SoapFault - faultcode: 'SOAP:Server' faultstring: 'Server Error' faultactor: 'null' detail: org.kxml2.kdom.Node@c40c80
        at org.ksoap2.serialization.SoapSerializationEnvelope.parseBody(Unknown Source)
        at org.ksoap2.SoapEnvelope.parse(Unknown Source)
        at org.ksoap2.transport.Transport.parseResponse(Unknown Source)
        at testeconexao.httpTransport22.call(httpTransport22.java:91)
        at testeconexao.Main.main(Main.java:33)

Aceito sugestões para conseguir fazer isso, preciso acessar um werbservice que o servidor exige autenticação, então aqui se baseia em uma autenticação do servidor.

Obrigado!!!

Criado 20 de março de 2009
Respostas 0
Participantes 1