martes, 21 de julio de 2009

Enviar datos POST o GET a un servidor desde android en modo JSON

Esta clase os puede ayudar para comunicarse con un servidor en base a datos simples. La idea es que tengáis un PerfilService (por ejemplo para enviar datos del perfil) que extienda esta clase JSONService y el metodo de enviar datos o recuperar datos llame a la funcion request.

public class JSONService {

public static final int METHOD_GET = 1;
public static final int METHOD_POST = 1;
/**
* Send data is an interface to send information to any JSONService.
*
*
* @param pvo
* @returns objeto json JSONObject
*/
public JSONObject request(String url, HashMap in, int method) {
Log.i(getClass().getSimpleName(), "send task - start");

JSONObject data=null;

UrlEncodedFormEntity entity=null;
if (in!=null) {
List pairs = new ArrayList();
for (Map.Entry i : in.entrySet()) {
if (i.getValue()!=null) {
pairs.add(new BasicNameValuePair(i.getKey(), i.getValue().trim()));
}
}
try {
entity = new UrlEncodedFormEntity(pairs);
} catch (UnsupportedEncodingException e) {
return null;
}

}


DefaultHttpClient client = new DefaultHttpClient();

//Instantiate a GET HTTP method
try {
HttpUriRequest metodo;
if (method==METHOD_GET) {
if (entity!=null) { url=url+"?"+JSONService.convertStreamToString(entity.getContent()).trim(); }
metodo=new HttpGet(url);
//((HttpGet)metodo).setEntity(entity);
} else {
metodo=new HttpPost(url);
if (entity!=null) {
((HttpPost)metodo).setEntity(entity);
}
}

HttpResponse response=client.execute(metodo);
InputStream is=response.getEntity().getContent();

data=new JSONObject(convertStreamToString(is));

return data;
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "sendDataException", e);
}

Log.i(getClass().getSimpleName(), "send task - end");
return data;
}


/**
* Convierte un InputStream en un String
* @param is
* @return
*/
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}


}

Y la clase PerfilService podría contener el siguiente método:



public boolean sendData(ProfileVO pvo)  {
Log.i(getClass().getSimpleName(), "send task - start");

HashMap params=new HashMap();
params.put("c1", pvo.getCampo1());
params.put("tel", pvo.getTelefono());


JSONObject resultado=request("http://www.example.com/sendData.php",params,JSONService.METHOD_GET);

Log.i(getClass().getSimpleName(), "send task - end");

try {
if (resultado==null) { return false; }
if (!("1".equals((String)resultado.get("ok")))) {
return false; //fail
}
} catch (JSONException e) {
Log.e(getClass().getSimpleName(),"excepcion sending data",e);
return false;
}

return true; //ok
}

Lo que si me pregunto es lo siguiente: ¿por que lo ha complicado tanto android con el tema de enviar parámetros? no hubiera sido mas facil hacer un conjutno de parametros independientes para get y post, y que en cada metodo, el httpclient los interpretara como debe?

2 comentarios:

Jordi dijo...

Por cierto, es MUY importante exponer tu contenido en el servidor como UTF-8... Asegurate de hacer un utf8_encode() a todos tus string en tu PHP.

Craken dijo...

disculpa sera que me puedas madar este proyecto estoy interesado en el manejo de json pero me marca un error en estas lineas

for (Map.Entry i : in.entrySet()) {
if (i.getValue()!=null) {
pairs.add(new BasicNameValuePair(i.getKey(), i.getValue().trim()));
}
}

exactamente en el in.entrySet() y en el trim() no se a que se debe ese problema espero una respuesta

Publicar un comentario