如何读取HTTP输入流?

45
下面粘贴的代码来自HttpURLConnection的Javadocs。
我收到以下错误信息:
readStream(in) 

我看到在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();   
    } 
5个回答

66

试试这段代码:

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
为了提高效率,result 也应该是一个 StringBuffer 对象。 - SD_Guru
10
建议使用 StringBuilder 而不是 StringBuffer,因为你不需要额外的同步开销。 - Joa Ebert
7
在单线程操作时,使用StringBuilder是很好的选择。当多个线程都要读写同一个对象时,应该使用StringBuffer - Muhammad Babar
1
这个问题特别针对没有openStream()的HttpURLConnection,所以我不确定为什么这会是一个好答案。 - Alkanshel

13

看起来文档只是用readStream()来表示:

好的,我们已经展示了如何获取InputStream,现在你的代码应该放在readStream()中执行。

因此,你应该编写自己的readStream()方法,以便执行你最初想要对数据执行的操作。


7

Spring有一个工具类可以实现这个功能:

import org.springframework.util.FileCopyUtils;

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

2

试试这段代码

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

可以假设编码是utf8吗? - Edd

0

一个完整的代码,可以以两种方式从Web服务中读取数据

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接