2012-03-24 10 views
36

El código pegado a continuación fue tomado de documentos de Java en HttpURLConnection.Cómo leer una secuencia de entrada http

me sale el siguiente error:

readStream(in) 

ya que no hay tal método.

Veo esto mismo en el general de la clase de URLConnection en URLConnection.getInputStream()

¿Dónde está readStream? El fragmento de código se proporciona a continuación:

URL url = new URL("http://www.android.com/"); 
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
    try 
    {  
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());  
     readStream(in); <-----NO SUCH METHOD 
    } 
    finally 
    {  
     urlConnection.disconnect(); 
    } 

Respuesta

54

Pruebe con este código:

InputStream in = address.openStream(); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
StringBuilder result = new StringBuilder(); 
String line; 
while((line = reader.readLine()) != null) { 
    result.append(line); 
} 
System.out.println(result.toString()); 
+6

Por razones de eficiencia, 'result' también debería ser un objeto StringBuffer. –

+7

Sugiero usar StringBuilder en lugar de StringBuffer ya que no necesita la sobrecarga de sincronización adicional. –

+3

'StringBuilder' es bueno para usar con una sola operación de rosca. 'StringBuffer' se debe utilizar cuando varios hilos están leyendo y escribiendo un vapor al mismo objeto. –

12

Parece que la documentación es sólo con readStream() a significar:

Ok, we've shown you how to get the InputStream, now your code goes in readStream()

por lo que debe o bien escribir su propio método readStream(), que hace lo que quería hacer con los datos en primer lugar.

3

primavera tiene una clase de util para ello:

import org.springframework.util.FileCopyUtils; 

InputStream is = connection.getInputStream(); 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
FileCopyUtils.copy(is, bos); 
String data = new String(bos.toByteArray()); 
2

prueba este código

String data = ""; 
InputStream iStream = httpEntity.getContent(); 
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8")); 
StringBuffer sb = new StringBuffer(); 
String line = ""; 

while ((line = br.readLine()) != null) { 
    sb.append(line); 
} 

data = sb.toString(); 
System.out.println(data); 
+0

¿Es seguro asumir que la codificación es utf8? – Edd

1

un código completo para la lectura de un servicio web en dos formas

public void buttonclick(View view) { 
    // the name of your webservice where reactance is your method 
    new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance"); 
} 

public class GetMethodDemo extends AsyncTask<String, Void, String> { 
    //see also: 
    // https://developer.android.com/reference/java/net/HttpURLConnection.html 
    //writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html 
    String server_response; 
    @Override 
    protected String doInBackground(String... strings) { 
     URL url; 
     HttpURLConnection urlConnection = null; 
     try { 
      url = new URL(strings[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      int responseCode = urlConnection.getResponseCode(); 
      if (responseCode == HttpURLConnection.HTTP_OK) { 
       server_response = readStream(urlConnection.getInputStream()); 
       Log.v("CatalogClient", server_response); 
      } 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      url = new URL(strings[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        urlConnection.getInputStream())); 
      String inputLine; 
      while ((inputLine = in.readLine()) != null) 
       System.out.println(inputLine); 
      in.close(); 
      Log.v("bufferv ", server_response); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
     Log.e("Response", "" + server_response); 
    //assume there is a field with id editText 
     EditText editText = (EditText) findViewById(R.id.editText); 
     editText.setText(server_response); 
    } 
} 
Cuestiones relacionadas