Accessing Webservice by Android - KSOAP2

Asked

Viewed 1,933 times

4

I am creating an Android APP and have to connect with the web service of my company to make the login system, I am using the lib KSOAP2 3.3.0.

The path of my WS is for example as: http://www.dominio.com/servicos/sambanet.asmx

My problem that happens:

09-04 10:57:52.835: W/System.err(19717): 
SoapFault - faultcode: 'soap:Client' faultstring: 
'Server did not recognize the value of HTTP Header SOAPAction:
http://www.dominio.com/servicos/ObterIdentificadorLoja.'
faultactor: 'null' detail: org.kxml2.kdom.Node@428e60d0

The variables stored for the connection:

private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.dominio.com/servicos/ws.asmx";
private final String SOAP_ACTION = "http://tempuri.org/ObterIdentificadorLoja";
private final String METHOD_NAME = "ObterIdentificadorLoja";
private String TAG = "LOGAR";

my WSDL is:

<wsdl:operation name="ObterIdentificadorLoja">
<soap:operation soapAction="http://tempuri.org/ObterIdentificadorLoja" style="document"/>

Source . Complete Java:

package com.testes.infovendas;

//Imports
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;

//KSOAP2 -- Lib de conexão Webservice SOAP
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

//Adicionais
import com.testes.infovendas.R;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class InfoVendas extends ActionBarActivity {

//Variáveis
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.dominio.com.br/servicos/ws.asmx";
private final String SOAP_ACTION = "http://tempuri.org/ObterIdentificadorLoja";
private final String METHOD_NAME = "ObterIdentificadorLoja";
private String TAG = "ASSYNC";
private static String cnpj_cpf_codclie, codloja, seguranca, identificadorloja;
Button b;
TextView tv;
EditText et1,et2,et3,et4;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    //Identificando cada campo e função
    et1 = (EditText) findViewById(R.id.editCodloja);
    et2 = (EditText) findViewById(R.id.editCPF);
    et3 = (EditText) findViewById(R.id.editUser);
    et4 = (EditText) findViewById(R.id.editPass);
    tv = (TextView) findViewById(R.id.login_informa);
    b = (Button) findViewById(R.id.btnEnviar);
    //Listener para quando clicar no botão Enviar
    b.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //Se todos os campos forem preenchidos, será retomado o login
            if (et1.getText().length() != 0 && et1.getText().toString() != "" || 
                    et2.getText().length() != 0 && et2.getText().toString() != "" || 
                    et3.getText().length() != 0 && et3.getText().toString() != "" || 
                    et4.getText().length() != 0 && et4.getText().toString() != "") {

                //Pega todas as informações escritas nos campos e adiciona em suas respectivas variáveis para uso do WS
                codloja = et1.getText().toString();
                cnpj_cpf_codclie = et2.getText().toString();
                seguranca = "chavesecreta";

                AsyncCallWS task = new AsyncCallWS();
                task.execute();

            } 
            //Se não for preenchido todos os campos, será retornado um TextView apenas informado para informar corretamente
            else {
                tv.setText("Por favor, insira todos os dados.");
            }
        }
    });
}

//Classe AsyncCallWS
private class AsyncCallWS extends AsyncTask<String, Void, Void> {

    //Retorna como null o valor do Identificador
    @Override
    protected Void doInBackground(String... params) {
        Log.i(TAG, "doInBackground");
        getIdentificador(cnpj_cpf_codclie, codloja, seguranca);
        return null;
    }

    //Mensagem e ação pós conclusão
    @Override
    protected void onPostExecute(Void result) {
        Log.i(TAG, "onPostExecute");
        tv.setText("identificador nº: " + identificadorloja + "  Conexão estabelecida. Realizando o login...");
    }

    //Mensagem ao clicar no botão Enviar
    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
        tv.setText("Estabelecendo conexão ao servidor...");
    }


    @Override
    protected void onProgressUpdate(Void... values) {
        Log.i(TAG, "onProgressUpdate");
    }

}

//Classe para obter os dados do Identificador
public void getIdentificador(String cnpj_cpf_codclie, String codloja, String seguranca) {
    //Create request
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    //Property which holds input parameters
    PropertyInfo identificadorPI = new PropertyInfo();
    //Set Name
    identificadorPI.setName("identificadorloja");
    //Set Value
    identificadorPI.setValue(identificadorloja);
    //Set dataType
    identificadorPI.setType(double.class);
    //Add the property to request object
    request.addProperty(identificadorPI);
    //Create envelope
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
    envelope.dotNet = true;
    //Set output SOAP object
    envelope.setOutputSoapObject(request);
    //Create HTTP call object
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
        //Invoke web service
        androidHttpTransport.call(SOAP_ACTION, envelope);
        //Get the response
        SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
        //Define identificadorloja como uma variável estática
        identificadorloja = response.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

I need to access the "Get identifier store", only it always gives the error of either the "HEADER could not be recognized" or "Timeout" or "Reference was not set to an instance or an object", and I tried several ways already..

Where I might be missing?

Note: I am emulating on my own phones (Moto X 4.4.4, Samsung Neo 4.1.3, Optimus One 2.3.3)

  • Test, first, all the resources of the webservice here http://www.soapclient.com/soaptest.html

  • everything works normally, @Igorronner! It’s a web service that my company has used for a long time! And we have over 1000 clients connected to it using the same things I’m trying to..

  • where you fill the identifier variable, I did not find.

  • is at the end of the code: identifier = sponse.toString(); It assigns to the identifier the answer of the webservice @Igorronner

  • you are setting the transponder valow in the Property without having yet?

  • not @Igorronner! In Try he is consuming the webservice, and the answer he delivers, he assigns to the identifier! For example, his answer is 2 (int), he assigns to the handle = "2", so it is shown on the screen as a test that has been completed.. In case with this error, only null appears because it cannot connect..

  • 1

    but that’s beside the point, the problem is he can’t connect...

  • Can someone help me?

Show 3 more comments

1 answer

2


After several attempts, I ended up solving the problem myself..

Follow the before and after source:

Before:

package com.testes.infovendas;

//Imports
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;

//KSOAP2 -- Lib de conexão Webservice SOAP
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

//Adicionais
import com.testes.infovendas.R;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class InfoVendas extends ActionBarActivity {

//Variáveis
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.dominio.com.br/servicos/ws.asmx";
private final String SOAP_ACTION = "http://tempuri.org/ObterIdentificadorLoja";
private final String METHOD_NAME = "ObterIdentificadorLoja";
private String TAG = "ASSYNC";
private static String cnpj_cpf_codclie, codloja, seguranca, identificadorloja;
Button b;
TextView tv;
EditText et1,et2,et3,et4;


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Identificando cada campo e função
et1 = (EditText) findViewById(R.id.editCodloja);
et2 = (EditText) findViewById(R.id.editCPF);
et3 = (EditText) findViewById(R.id.editUser);
et4 = (EditText) findViewById(R.id.editPass);
tv = (TextView) findViewById(R.id.login_informa);
b = (Button) findViewById(R.id.btnEnviar);
//Listener para quando clicar no botão Enviar
b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        //Se todos os campos forem preenchidos, será retomado o login
        if (et1.getText().length() != 0 && et1.getText().toString() != "" || 
                et2.getText().length() != 0 && et2.getText().toString() != "" || 
                et3.getText().length() != 0 && et3.getText().toString() != "" || 
                et4.getText().length() != 0 && et4.getText().toString() != "") {

            //Pega todas as informações escritas nos campos e adiciona em suas respectivas variáveis para uso do WS
            codloja = et1.getText().toString();
            cnpj_cpf_codclie = et2.getText().toString();
            seguranca = "chavesecreta";

            AsyncCallWS task = new AsyncCallWS();
            task.execute();

        } 
        //Se não for preenchido todos os campos, será retornado um TextView apenas informado para informar corretamente
        else {
            tv.setText("Por favor, insira todos os dados.");
        }
    }
});
}

//Classe AsyncCallWS
private class AsyncCallWS extends AsyncTask<String, Void, Void> {

//Retorna como null o valor do Identificador
@Override
protected Void doInBackground(String... params) {
    Log.i(TAG, "doInBackground");
    getIdentificador(cnpj_cpf_codclie, codloja, seguranca);
    return null;
}

//Mensagem e ação pós conclusão
@Override
protected void onPostExecute(Void result) {
    Log.i(TAG, "onPostExecute");
    tv.setText("identificador nº: " + identificadorloja + "  Conexão estabelecida. Realizando o login...");
}

//Mensagem ao clicar no botão Enviar
@Override
protected void onPreExecute() {
    Log.i(TAG, "onPreExecute");
    tv.setText("Estabelecendo conexão ao servidor...");
}


@Override
protected void onProgressUpdate(Void... values) {
    Log.i(TAG, "onProgressUpdate");
}

}

//Classe para obter os dados do Identificador
public void getIdentificador(String cnpj_cpf_codclie, String codloja, String seguranca) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Property which holds input parameters
PropertyInfo identificadorPI = new PropertyInfo();
//Set Name
identificadorPI.setName("identificadorloja");
//Set Value
identificadorPI.setValue(identificadorloja);
//Set dataType
identificadorPI.setType(double.class);
//Add the property to request object
request.addProperty(identificadorPI);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11);
envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    //Invoke web service
    androidHttpTransport.call(SOAP_ACTION, envelope);
    //Get the response
    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
    //Define identificadorloja como uma variável estática
    identificadorloja = response.toString();

} catch (Exception e) {
    e.printStackTrace();
}
}

}

Afterward:

//Variáveis
private static final String SOAP_ACTION = "http://tempuri.org/ObterIdentificadorLoja";
private static final String METHOD_NAME = "ObterIdentificadorLoja";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.dominio.com.br/servicos/ws.asmx";
private PropertyInfo piCodLoja;
private PropertyInfo piCPF;
private PropertyInfo piSenha;
private String TAG = "ASSYNC";         
private static String cnpj_cpf_codclie, codloja, identificadorloja;
private static String seguranca = "SECRET";
//Classe para obter os dados do Identificador
public void getIdentificador(String cnpj_cpf_codclie, String codloja, String seguranca) {
    //Create request
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    piCodLoja = new PropertyInfo();
    piCodLoja.setName("codloja");
    piCodLoja.setValue(et1.getText().toString());//get the string that is to be sent to the web service
    piCodLoja.setType(String.class);
    request.addProperty(piCodLoja);

    piCPF = new PropertyInfo();
    piCPF.setName("cnpj_cpf_codclie");
    piCPF.setValue(et2.getText().toString());//get the string that is to be sent to the web service
    piCPF.setType(String.class);
    request.addProperty(piCPF);

    piSenha = new PropertyInfo();
    piSenha.setName("seguranca");
    piSenha.setValue("Secret");//get the string that is to be sent to the web service
    piSenha.setType(String.class);
    request.addProperty(piSenha);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.