Httpurlconnection with Mysql and Webservice

Asked

Viewed 120 times

0

I am trying to create a connection class to feed information into a Mysql database as follows:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class conexao {

    public static String postDados(String urlUsuario,String parametrosUsuario){
        URL url;
        HttpURLConnection connection = null;

        try{
            url = new URL(urlUsuario);
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(parametrosUsuario.getBytes().length));
            connection.setRequestProperty("Content-Language", "pt-BR");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            outputStreamWriter.write(parametrosUsuario);
            outputStreamWriter.flush();

            InputStream inputStream = connection.getInputStream();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String linha;
            StringBuffer resposta = new StringBuffer();

            while((linha = bufferedReader.readLine()) != null){
                resposta.append(linha);
                resposta.append('\r');
            }

            bufferedReader.close();

            return resposta.toString();

        }
        catch (Exception erro){
            return null;
        }
        finally {
            if(connection != null){
                connection.disconnect();
            }
        }
    }

}

When I run the application and do some logging the connection works, but the parameters are coming empty in the database as if generating a INSERT with blank information.

Because you are not properly feeding the information into my DB and what is the correct way to create a connection class using HttpURLConnection?

Follows my class of record:

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TelaCadastro extends AppCompatActivity {

    private EditText edtNome;
    private EditText edtEmail;
    private EditText edtSenha;
    private Button btnCancelar;
    private Button btnRegistrar;

    String url = "";
    String parametros = "";

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

        edtNome = (EditText) findViewById(R.id.edtNomeId);
        edtEmail = (EditText) findViewById(R.id.edtEmailId);
        edtSenha = (EditText) findViewById(R.id.edtSenhaId);
        btnCancelar = (Button) findViewById(R.id.btnCancelarId);
        btnRegistrar = (Button) findViewById(R.id.btnRegistrarId);

        btnCancelar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cancela = new Intent(TelaCadastro.this,MainActivity.class);
                startActivity(cancela);
            }
        });

        btnRegistrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                if(networkInfo != null && networkInfo.isConnected()) {

                    String nome = edtNome.getText().toString();
                    String email = edtEmail.getText().toString();
                    String senha = edtSenha.getText().toString();

                    if(nome.isEmpty() || email.isEmpty() || senha.isEmpty()){
                        Toast.makeText(TelaCadastro.this, "Todos os campos devem ser preenchidos", Toast.LENGTH_LONG).show();
                    }
                    else{
                        url = "http://192.168.1.30/mysqlapp/registro.php";
                        parametros = "nome="+nome+"&email="+email+"&senha="+senha;
                        new Solicitadados().execute(url);
                    }

                }
                else{
                    Toast.makeText(TelaCadastro.this, "Não foi possivel conectar", Toast.LENGTH_LONG).show();
                }



            }
        });
    }
    private class Solicitadados extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... urls) {
            return conexao.postDados(urls[0], parametros);
        }
        @Override
        protected void onPostExecute(String resultado) {
            Toast.makeText(TelaCadastro.this,resultado,Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onBackPressed() {

    }
}

As follows within the connection class it worked by changing the method postDados, I just don’t want to String parametrosUsuario.

public static String postDados(String urlUsuario) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlUsuario);
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Language", "pt-BR");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            InputStream inputStream = connection.getInputStream();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String linha;
            StringBuffer resposta = new StringBuffer();

            while((linha = bufferedReader.readLine()) != null){
                resposta.append(linha);
                resposta.append('\r');
            }

            bufferedReader.close();

            return resposta.toString();
        }
        catch (Exception erro){
            return null;
        }
        finally {
            if(connection != null){
                connection.disconnect();
            }
        }

    }

In the class of register a URL is as follows:

url = "http://192.168.1.30/mysqlapp/registro.php?nome="+nome+"&email="+email+"&senha="+senha;' 
  • Aode is the method that executes the query ?

  • Take a look here https://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post

No answers

Browser other questions tagged

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