Android with PHP Web Service

Asked

Viewed 1,610 times

5

Someone has an example of what it takes to recover data from an external database without using JDBC ?

2 answers

0

0

Httpclient method which is very simple, I will put an example. It has get methods that does not send any parameters to the Web Service and has the Post that sends parameters, (as many as you want...)

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

public class ConexaoHttpClient {

public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient httpClient;

private static HttpClient getHttpClient(){
    if (httpClient == null){
        httpClient = new DefaultHttpClient();

        final HttpParams httpParams = httpClient.getParams();

        HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(httpParams, HTTP_TIMEOUT);
    }
    return httpClient;
}

public static String executaHttpPost(String url, ArrayList<NameValuePair> parametrosPost) throws Exception{
    BufferedReader bufferedReader = null;
    try{
        HttpClient client = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parametrosPost);
        httpPost.setEntity(formEntity);
        HttpResponse httpResponse = client.execute(httpPost);
        bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        StringBuffer stringBuffer = new StringBuffer("");
        String line = "";
        String LS = System.getProperty("line.separator");

        while ((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line + LS);
        }
        bufferedReader.close();

        String resultado = stringBuffer.toString();
        return resultado;
    }finally{
        if (bufferedReader != null){
            try{
                bufferedReader.close();
            }catch(IOException erro){
                erro.printStackTrace();
            }
        }

    }

}

public static String executaHttpGet(String url) throws Exception{
    BufferedReader bufferedReader = null;
    try{
        HttpClient client = getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setURI(new URI(url));
        HttpResponse httpResponse = client.execute(httpGet);
        bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        StringBuffer stringBuffer = new StringBuffer("");
        String line = "";
        String LS = System.getProperty("line.separator");

        while ((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line + LS);
        }
        bufferedReader.close();

        String resultado = stringBuffer.toString();
        return resultado;
    }finally{
        if (bufferedReader != null){
            try{
                bufferedReader.close();
            }catch(IOException erro){
                    erro.printStackTrace();
                }
            }

        }

    }

}

This is a method as an example, for a login screen:

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import br.com.projetotcc.conexao.ConexaoHttpClient;
import br.com.projetotcc.utilitarios.Funcoes;
import br.com.projetotcc.visao.Activity_Atencao;
import br.com.projetotcc.visao.Activity_Principal;

public class Dao extends Activity{

String[] idPacientes;
String[] Opcao;
int posicaoPaciente;
int posicaoOpcao;

Context context;
Funcoes funcoes = new Funcoes();

public Dao(Context context){
    this.context = context;
}

public void Logar(Context context, String cpf, String senha, String ip, String arquivo) throws Exception{
    String urlPost = "http://"+ip.toString()+"/projetotcc/android/"+arquivo+"";
    ArrayList<NameValuePair> parametrosPost = new ArrayList<NameValuePair>();
    parametrosPost.add(new BasicNameValuePair("cpf", cpf));
    parametrosPost.add(new BasicNameValuePair("senha", senha));

    String respostaRetornada = null;
    Log.i("Entrou", "Vai entrar no try");

    respostaRetornada = ConexaoHttpClient.executaHttpPost(urlPost, parametrosPost);
    Log.i("Entrou", "Entrou");
    String resposta = respostaRetornada.toString();
    resposta = resposta.replaceAll("\\s+", "");

    Log.i("Logar", "Resposta: "+resposta);

    if (resposta.equals("1")){
        finish();
        Intent intent = new Intent(context, Activity_Principal.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("senha", Integer.parseInt(senha));
        intent.putExtra("cpf", cpf);
        context.startActivity(intent);
        finish();
    }else{
        Toast.makeText(this, "Usuário e ou senha inválida", Toast.LENGTH_LONG).show();
    }
}

And this other to return the patient ID:

public String[] pegarIdPaciente(Context context, String nome, String ip, String arquivo){
    String urlPost3 = "http://"+ip+"/projetotcc/android/"+arquivo+"";
    ArrayList<NameValuePair> parametrosPost3 = new ArrayList<NameValuePair>();
    parametrosPost3.add(new BasicNameValuePair("nomePac", nome));

    String respostaRetornada3 = null;

    try{
        respostaRetornada3 = ConexaoHttpClient.executaHttpPost(urlPost3, parametrosPost3);
        Log.i("Entrou", "Entrou descobrirIdPaciente");
        String resposta3 = respostaRetornada3.toString();
        resposta3 = resposta3.replaceAll("\\s+", "");

        Log.i("ID do Paciente", "ID do Paciente: "+resposta3);

        char separador3  = '#';
        int contaPacientes3 = 0;

        for (int i=0; i < resposta3.length(); i++){
            if (separador3 == resposta3.charAt(i)){
                contaPacientes3++;
                idPacientes  = new String[contaPacientes3];
            }
        }

        char caracterLido = resposta3.charAt(0);
        String nome1  = "";

        for (int i=0; caracterLido != '^'; i++){
            caracterLido = resposta3.charAt(i);
            Log.i("Chars", "Chars do paciente"+caracterLido);

            if (caracterLido != '#'){
                nome1+= (char) caracterLido;
            }else{
                Log.i("Nome", "Nome: "+nome1);
                idPacientes[posicaoPaciente] =""+ nome1;
                Log.i("Nome posição ["+posicaoPaciente+"]", ""+idPacientes[posicaoPaciente]);
                posicaoPaciente = posicaoPaciente + 1;
                nome1 = "";
            }
        }

    }catch(Exception erro){
        funcoes.mensagemSimples(context, "Erro", "Erro: "+erro);
    }
    return idPacientes;
}

You only need Internet permission

Browser other questions tagged

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