Lectura de la respuesta HttpPost

Estoy usando este código para publicar una solicitud en un servidor http:

HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://192.168.0.1/test.php" ); HttpResponse response = null; try { List< NameValuePair > nameValuePairs = new ArrayList< NameValuePair >( 1 ); nameValuePairs.add( new BasicNameValuePair( "num", "2" ) ); post.setEntity( new UrlEncodedFormEntity( nameValuePairs ) ); response = client.execute( post ); } catch( ClientProtocolException e ) { ... } catch( IOException e ) { ... } 

La respuesta no es más que una simple String . ¿Cómo puedo leer esta respuesta como una String ? No parece que HttpResponse tenga un método para hacer esto directamente.

He creado este método auxiliar para enviar datos y encabezados especiales por método POST en Android (los encabezados HashMap podrían estar vacíos si no tienes encabezados personalizados):

 public static String getStringContent(String uri, String postData, HashMap<String, String> headers) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(); request.setURI(new URI(uri)); request.setEntity(new StringEntity(postData)); for(Entry<String, String> s : headers.entrySet()) { request.setHeader(s.getKey(), s.getValue()); } HttpResponse response = client.execute(request); InputStream ips = response.getEntity().getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8")); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK) { throw new Exception(response.getStatusLine().getReasonPhrase()); } StringBuilder sb = new StringBuilder(); String s; while(true ) { s = buf.readLine(); if(s==null || s.length()==0) break; sb.append(s); } buf.close(); ips.close(); return sb.toString(); } 

response.getStatusLine(); // Para leer la línea de estado

 org.apache.http.util.EntityUtils.toString(response.getEntity()); 
  • ¿Cómo realizar un seguimiento de los elementos seleccionados en un RecyclerView en Android?
  • Cómo llamar a fragment method de la actividad principal
  • Barra de herramientas y Fragmento
  • Ejecutar Android App Error (FATAL EXCEPTION: principal Proceso: PID: 14099)
  • Integrar roboelectric con android studio con gradle siempre da paquetes org.junit no existe error
  • Cómo agregar rectángulos encima del rectángulo existente en el lienzo
  • ¿Cómo puedo mostrar un círculo de actividad holo-temático?
  • Android Development: Obtención de datos desde la Web
  • ¿Cómo utilizo un proyecto Java que requiere un nivel de cumplimiento de 1.7 en una ruta de construcción de proyecto de Android?
  • ¿Reutilizando la galería de imágenes predeterminada de Android?
  • Cómo generar simple-xml java objeto anotado desde el esquema xsd
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.