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, HashMapin, int method) {
Log.i(getClass().getSimpleName(), "send task - start");
JSONObject data=null;
UrlEncodedFormEntity entity=null;
if (in!=null) {
Listpairs = new ArrayList ();
for (Map.Entryi : 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");
HashMapparams=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?