Send problem in Webservice call (SOAP_ACTION, envelope)

2

I have a service that when accessed by the browser it shows the xml through the " link command. p>

I made a test application to test the connection and when it arrives at the command Tranport.call(SOAP_ACTION, envelope) the error log is displaying error messages related to the transport. Error Below:

01-22 19:42:39.515: W/System.err(27880): android.os.NetworkOnMainThreadException 01-22 19:42:39.515: W/System.err(27880):   
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166) 01-22 19:42:39.515: W/System.err(27880):   
    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 01-22 19:42:39.515: W/System.err(27880):   
    at libcore.io.IoBridge.connectErrno(IoBridge.java:144) 01-22 19:42:39.515: W/System.err(27880):     
    at libcore.io.IoBridge.connect(IoBridge.java:112) 01-22 19:42:39.515: W/System.err(27880):  
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 01-22 19:42:39.515: W/System.err(27880):  
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460) 01-22 19:42:39.515: W/System.err(27880):  
    at java.net.Socket.connect(Socket.java:833) 01-22 19:42:39.525: W/System.err(27880):    
    at com.android.okhttp.internal.Platform.connectSocket(Platform.java:131) 01-22 19:42:39.525: W/System.err(27880):   
    at com.android.okhttp.Connection.connect(Connection.java:101) 01-22 19:42:39.525: W/System.err(27880):  
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294) 01-22 19:42:39.525: W/System.err(27880):    
    at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255) 01-22 19:42:39.525: W/System.err(27880):  
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206) 01-22 19:42:39.525: W/System.err(27880):    
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) 01-22 19:42:39.525: W/System.err(27880):  
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89) 01-22 19:42:39.525: W/System.err(27880):   
    at org.ksoap2.transport.ServiceConnectionSE.connect(ServiceConnectionSE.java:76) 01-22 19:42:39.525: W/System.err(27880):   
    at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:152) 01-22 19:42:39.525: W/System.err(27880):     
    at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:95) 01-22 19:42:39.525: W/System.err(27880):  
    at com.example.teste2.MainActivity.autenticausuario(MainActivity.java:164) 01-22 19:42:39.525: W/System.err(27880):     
    at com.example.teste2.MainActivity.onClick(MainActivity.java:194) 01-22 19:42:39.525: W/System.err(27880):  
    at android.view.View.performClick(View.java:4640) 01-22 19:42:39.525: W/System.err(27880):  
    at android.view.View$PerformClick.run(View.java:19425) 01-22 19:42:39.525: W/System.err(27880):     
    at android.os.Handler.handleCallback(Handler.java:733) 01-22 19:42:39.525: W/System.err(27880):     
    at android.os.Handler.dispatchMessage(Handler.java:95) 01-22 19:42:39.525: W/System.err(27880):     
    at android.os.Looper.loop(Looper.java:146) 01-22 19:42:39.525: W/System.err(27880):     
    at android.app.ActivityThread.main(ActivityThread.java:5593) 01-22 19:42:39.525: W/System.err(27880):   
    at java.lang.reflect.Method.invokeNative(Native Method) 01-22 19:42:39.525: W/System.err(27880):    
    at java.lang.reflect.Method.invoke(Method.java:515) 01-22 19:42:39.525: W/System.err(27880):    
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 01-22 19:42:39.525: W/System.err(27880):    
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 01-22 19:42:39.525: W/System.err(27880):   
    at dalvik.system.NativeStart.main(Native Method) 01-22 19:42:39.535: D/Toast(27880):  checkMirrorLinkEnabled returns : false 01-22 19:42:39.535: D/Toast(27880): showing allowed

FOLLOWS THE APPLICATION CODE:

public class MainActivity extends Activity implements OnClickListener{

    private static       String      SOAP_ACTION = null;
    private static       String      METHOD_NAME = null;
    private static final String      NAMESPACE   = "http://192.168.0.102:8080/";
    private static final String      URL         = "http://192.168.0.102:8080/ServicoWeb1/services/CServico";
    private ImageView imLogo;
    private EditText edtLogin;
    private EditText edtSenha;
    private TextView textLogin;
    private TextView textSenha;
    private String Login;
    private String Senha;
    private TableLayout tabela;
    private TableRow linha;
    private Button validar;
    private WindowManager wm;
    private int width;
    private int heigth;
    private int Retorno;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wm = (WindowManager) this.getSystemService(this.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        width = display.getHeight();
        heigth = display.getWidth();

        //setando variáveis de referencia
        imLogo = new ImageView(this);
        imLogo = (ImageView) findViewById(R.drawable.logo_fiat);        
        //imLogo.setOnClickListener(this);

        tabela = new TableLayout(this);
        tabela.setGravity(Gravity.CENTER);
        tabela.setColumnStretchable(1, true);
        tabela = (TableLayout)findViewById(R.id.tabela1);
        textLogin = new TextView(this);
        textLogin.setText("Login");
        textSenha = new TextView(this);
        textSenha.setText("Senha");
        edtLogin = new EditText(this);
        edtSenha = new EditText(this);
        edtSenha.setTransformationMethod(new PasswordTransformationMethod());
        validar = new Button(this);
        validar.setOnClickListener(this);
        validar.setText("Entrar");      

        linha = new TableRow (this);
        linha.setGravity(Gravity.CENTER);
        linha.addView(textLogin);
        tabela.addView(linha);

        linha = new TableRow (this);
        linha.setGravity(Gravity.CENTER);
        linha.addView(edtLogin);
        tabela.addView(linha);

        linha = new TableRow (this);
        linha.setGravity(Gravity.CENTER);
        linha.addView(textSenha);
        tabela.addView(linha);

        linha = new TableRow (this);
        linha.setGravity(Gravity.CENTER);
        linha.addView(edtSenha);
        tabela.addView(linha);

        linha = new TableRow (this);
        linha.setGravity(Gravity.CENTER);
        linha.addView(validar);
        tabela.addView(linha);

        //Iniciando tratativas para webservices
//      if(isOnline()==false)
//      {
//          AlertDialog.Builder alerta =  
//                  new AlertDialog.Builder(this).setTitle("Atenção!").setMessage("Falha ao tentar conectar a internet ou servidor indisponível." );                       
//          alerta.setNeutralButton("Continuar", null);    
//          alerta.show();                      
//          return;                 
//      }               
    }


    /*************************************************    
     *METODO QUE VERIFICA SE HÁ CONEXÃO COM A INTERNET    
     *************************************************/
    public static boolean isOnline() {
        try {
            InetAddress.getByName("google.ca").isReachable(3);
            return true;
        } catch (UnknownHostException e){           
            return false;
        } catch (IOException e){
            return false;
        }
    }

    /*********************************************************************************
     *              METODO PARA CARREGAR A INTERFACE DE CONTATO
     * *******************************************************************************/ 
    private SoapPrimitive autenticausuario(String prNome, String prsenha){

        System.out.println("AUTENTICANDO");
        SoapPrimitive sp = null;
        SOAP_ACTION = "autenticaReturn";
        METHOD_NAME = "autentica";      
        System.out.println("PREPARAR");
        try {           
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);    
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);             

            PropertyInfo pi = new PropertyInfo();
            String a = ""+prNome+"/"+prsenha;
            pi.setName("dados");
            pi.setValue(a);
            pi.setType(String.class);       

            request.addProperty(pi);    
            HttpTransportSE Transport = new HttpTransportSE(URL);
            Transport.debug = true;
            envelope.setOutputSoapObject(request);          
            Transport.call(SOAP_ACTION, envelope);
            System.out.println("Aqui");
            SoapObject body = (SoapObject)envelope.bodyIn;                          
            SoapObject result= (SoapObject)envelope.getResponse();//Instancia um vetor de objetos do tipo soapObject            

            String valida = result.toString();
            System.out.println("PARTE 5"+valida);
            if(valida.equals("ok")){
            System.out.println(valida);
            Retorno = 1;
            }else Retorno = 0;

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


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        //valida password. esta informação pode ser buscada no banco de dados.

        Login = edtLogin.getText().toString();
        System.out.println(Login);
        Senha = edtSenha.getText().toString();
        System.out.println(Senha);

        this.autenticausuario(Login, Senha);

        if(Retorno==1)
        {
            System.out.println("largura:"+width);
            System.out.println("largura:"+heigth);
            //mensagem de confirmação
            Toast.makeText(this, "Usuário autencitado", Toast.LENGTH_SHORT).show();
            //chama a próxima activity/tela
            Intent prox_tela = new Intent(this, tela_opcao.class);
            startActivity(prox_tela);
        }else
            Toast.makeText(this, "Login ou senha incorreto!", Toast.LENGTH_SHORT).show();       
    }

}
    
asked by anonymous 22.01.2015 / 23:48

2 answers

1

Good practices recommend using a class that inherits from an AsyncTask for network tasks. By doing this the requests will be performed on a separate Thread which then updates its UI Thread (Screen / Activity).

Based on your first error line: android.os.NetworkOnMainThreadException .

It may be noted that it is an android system error due to network usage on the main Thread.

This video explains well how an AsyncTask works.

If you do not resolve it, you should also review the composition of your SOAP request, noting that everything is in accordance with your WSDL.

    
24.01.2015 / 01:49
1

As pointed out by @FeedProject, you can not call the WebService in Thread Principal.

But if for some reason you do not want to use AsyncTask , such as having greater control over the threads, you can use HandlerThread and emulate a AsyncTask .

The code below assumes that type X will be the data input and type Y the output.

public abstract class AsyncRunnable<X, Z> implements Runnable {

    private static HandlerThread handlerThread;
    private Handler handler;
    protected X[] parametros;
    protected CountDownLatch latch;
    protected Z retorno;

    public void run() {

    }

    protected AsyncRunnable() {
        if (AsyncRunnable.handlerThread == null) {
            AsyncRunnable.handlerThread =  new HandlerThread("WebServiceThread", android.os.Process.THREAD_PRIORITY_BACKGROUND);
            AsyncRunnable.handlerThread.start();
        }
        this.handler = new Handler(AsyncRunnable.handlerThread.getLooper());
    }

    public AsyncRunnable execute(X... parametros) {
        this.parametros = parametros;
        this.latch = new CountDownLatch(1);

        this.handler.post(this);
        return this;
    }

    public Z get() {
        try {
            latch.await();
        } catch (Exception ignore) {

        }
        return this.retorno;
    }
}

If you need to call it:

AsyncRunnable<Object, Object> asyncRunnable = new AsyncRunnable<Object, Object>() {
    @Override
    public void run() {
        super.run();
        this.retorno = webServiceClient.CallMethod(this.parametros[0], this.parametros[1]);
    }
};

Object[] input = new Object[] { new Object(), new Object() };
Object output = asyncRunnable.execute(input).get();

The only difference from the above code for AsyncTask is that all calls to the WebService will be performed by the same Thread .

Remembering that this is only an alternative to AsyncTask .

    
23.02.2015 / 20:58