User login with Webservice

Asked

Viewed 334 times

1

I would like to ask the connoisseurs of Java (Android) to guide me in this code:

Mainactivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d("TESTE", "Iniciou MainActivity");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    txt_usuario = (EditText) findViewById(R.id.usuario);
    txt_senha = (EditText) findViewById(R.id.senha);
    btn_login = (Button) findViewById(R.id.btn_login);

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String user = txt_usuario.getText().toString();
            String pssw = txt_senha.getText().toString();

            SistemaHttp sHttp = new SistemaHttp(getBaseContext());
            String ret = sHttp.retornaUsuario(user, pssw);
            retornoLogin(ret);

        }
    });
}

private void retornoLogin(String retorno)
{
    Log.d("TESTE", "(MainActivity) retornoLogin(" + retorno + ")");
    if (retorno.equals("OK"))
    {
        Toast.makeText(this, "Logado com sucesso", Toast.LENGTH_SHORT).show();
    }
    else if (retorno.equals("ERRO"))
    {
        Toast.makeText(this, "Login incorreto", Toast.LENGTH_SHORT).show();
    }
}

Systemshttp:

public static final String SERVIDOR = "http://www.exemplo.com.br";
private static final String WEBSERVICE_URL = SERVIDOR + "/webservicesistema.php";

private Context mContext;

public SistemaHttp(Context ctx)
{
    mContext = ctx;
}

public String retornaUsuario(String user, String pssw)
{
    Log.d("TESTE", "(SistemaHttp) retornaUsuario(" + user + ", " + pssw + ")");
    String met = "GET";
    String resp = "";

    try
    {
        if (enviarRequisicao(met, user, pssw))
        {
            resp = "OK";
            Log.d("TESTE", "(SistemaHttp) retornaUsuario() enviarRequisicao(" + met + ", " + user + ", " + pssw + ") OK");
        }
        else
        {
            resp = "ERRO";
        }

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

    return resp;
}

private boolean enviarRequisicao(String metodoHttp, String user, String pssw) throws Exception
{

    Log.d("TESTE", "(SistemaHttp) enviarRequisicao(" + metodoHttp + ", " + user + ", " + pssw + ")");

    boolean sucesso = false;
    boolean doOutput = !"DELETE".equals(metodoHttp);
    String url = WEBSERVICE_URL;

    HttpURLConnection conexao = abrirConexao(url, metodoHttp, doOutput);

    if (doOutput)
    {
        OutputStream os = conexao.getOutputStream();
        os.write(loginToJsonBytes(user, pssw));
        os.flush();
        os.close();
    }

    int responseCode = conexao.getResponseCode();
    Log.d("TESTE", "(SistemaHttp) enviarRequisicao() responseCode == " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK)
    {
        Log.d("TESTE", "(SistemaHttp) enviarRequisicao() responseCode == HttpURLConnection.HTTP_OK");
        InputStream is = conexao.getInputStream();
        String s = streamToString(is);
        is.close();
        // JSONObject json= new JSONObject(s);
        // hotel.idServidor = json.getInt("id");
        sucesso = true;
    }
    else
    {
        Log.d("TESTE", "(SistemaHttp) enviarRequisicao() responseCode == HttpURLConnection.ERROR");
        sucesso = false;
    }

    conexao.disconnect();
    return sucesso;
}

private HttpURLConnection abrirConexao(String url, String metodo, boolean doOutput) throws Exception
{
    Log.d("TESTE", "(SistemaHttp) abrirConexao(" + url + ", " + metodo + ", " + doOutput + ")");
    URL urlCon = new URL(url);

    HttpURLConnection conexao = (HttpURLConnection) urlCon.openConnection();
    conexao.setReadTimeout(15000);
    conexao.setConnectTimeout(15000);
    conexao.setRequestMethod(metodo);
    conexao.setDoInput(true);
    conexao.setDoOutput(doOutput);

    if (doOutput)
    {
        conexao.addRequestProperty("Content-Type", "application/json");
    }

    conexao.connect();
    return conexao;
}

private byte[] loginToJsonBytes(String user, String pssw) {

    Log.d("TESTE", "(SistemaHttp) loginToJsonBytes(" + user + ", " + pssw + ")");

    try {
        JSONObject jsonLogin = new JSONObject();
        jsonLogin.put("usuario", user);
        jsonLogin.put("senha", pssw);

        String json = jsonLogin.toString();

        return json.getBytes();
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }

    return null;
}

private String streamToString(InputStream is) throws Exception {
    Log.d("TESTE", "(SistemaHttp) Iniciou streamToString()");

    byte[] bytes = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int lidos;

    while ((lidos = is.read(bytes)) > 0)
    {
        baos.write(bytes, 0, lidos);
    }

    return new String(baos.toByteArray());
}

The logic is the following, when clicking on the button get the values that were filled in EditTexts and send to the method retornaUsuario(user, pssw) of the Systemshttp class, where it takes the data and makes an HTTP request to webservice.php and returns whether there is the user and password in the database, and the return methodLogin from Mainactivity displays a Toast according to the return.

The excerpt from webservice.php this one:

$metodoHttp = $_SERVER['REQUEST_METHOD'];

if ($metodoHttp == 'GET') {
    $stmt = $conn->prepare(
        "SELECT * FROM hotel_db.usuarios WHERE login=? and senha=?");
    $json = json_decode(file_get_contents('php://input'));
    $endereco = $json->{'login'};
    $estrelas = $json->{'senha'};
    $stmt->bind_param("ss", $nome, $login);
    $stmt->execute();
    $stmt->close();
    $id = $conn->insert_id;
    $jsonRetorno = array("id"=>$id);
    echo json_encode($jsonRetorno);
} 

In the Android part I put some logs to see how far the code ran and it reaches the method abrirConexao() and a blue message appears written:

W/System.err: android.os.Networkonmainthreadexception W/System.err: at android.os.Strictmode$Androidblockguardpolicy.onNetwork(Strictmode.java:1147) W/System.err: at java.net.Inetaddress.lookupHostByName(Inetaddress.java:418) W/System.err: at java.net.Inetaddress.getAllByNameImpl(Inetaddress.java:252) W/System.err: at java.net.Inetaddress.getAllByName(Inetaddress.java:215) W/System.err: at com.android.okhttp.Hostresolver$1.getAllByName(Hostresolver.java:29) W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(Routeselector.java:232) W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(Routeselector.java:124) W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(Httpengine.java:272) W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(Httpengine.java:211) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(Httpurlconnectionimpl.java:382) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(Httpurlconnectionimpl.java:106) W/System.err: at with.exemplo.example.SistemaHttp.open Output(Systemshttp.java:122) W/System.err: at with.exemplo.example.SistemaHttp.send Want(Systemshttp.java:72) W/System.err: at com.exemplo.exemplo.SistemaHttp.retornaUsuario(Systemshttp.java:45) W/System.err: at com.exemplo.exemplo.Mainactivity$1.onClick(Mainactivity.java:44) W/System.err: at android.view.View.performClick(View.java:4780) W/System.err: at android.view.View$Performclick.run(View.java:19866) W/System.err: at android.os.Handler.handleCallback(Handler.java:739) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95) W/System.err: at android.os.Looper.loop(Looper.java:135) W/System.err: at android.app.Activitythread.main(Activitythread.java:5254) W/System.err: at java.lang.reflect.Method.invoke(Native Method) W/System.err: at java.lang.reflect.Method.invoke(Method.java:372) W/System.err: at com.android.Internal.os.Zygoteinit$Methodandargscaller.run(Zygoteinit.java:903) W/System.err: at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:698)

1 answer

1


From Android 3.0, network connections are no longer allowed in the thread main (also known as UI Thread). Network operations on that thread have the effect of freezing the graphical interface until the request returns a result, which provides a bad user experience.

One solution is to make your operation within a AsyncTask.

I’m not gonna repeat how to do this, because here at Stackoverflow we already have an explanation of how to do it. A official documentation also has an easy to understand example. If facing difficulties, feel free to open a new question.

  • Thanks guy I had heard about in asyncTask but I wasn’t sure when to use (or where) I will give an extra step and see if I can put her in my case.

Browser other questions tagged

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