Подтвердить что ты не робот

Как читать входной поток http

Код, вставленный ниже, был взят из java docs на HttpURLConnection.

Я получаю следующую ошибку:

readStream(in) 

поскольку такого метода нет.

Я вижу то же самое в Обзор класса для URLConnection в URLConnection.getInputStream()

Где readStream? Ниже приведен фрагмент кода:

 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();   
    } 
4b9b3361

Ответ 1

Попробуйте с помощью этого кода:

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());

Ответ 2

Похоже, документация просто использует readStream() для обозначения:

Хорошо, мы показали вам, как получить InputStream, теперь ваш код идет в readStream()

Итак, вы должны либо написать свой собственный метод readStream(), который делает все, что вы хотели сделать с данными в первую очередь.

Ответ 3

Spring имеет класс util для этого:

import org.springframework.util.FileCopyUtils;

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

Ответ 4

попробуйте этот код

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);

Ответ 5

полный код для чтения из веб-службы двумя способами

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);
    }
}