太过困惑!使用BufferReader
,InputStream
和StringBuffer
的唯一目的是什么?为什么要使用它们以及我们应该以什么样的序列/模式对它们进行编码。我最近遇到了一大堆代码,同时了解如何在android中使用HTTP
发送和接收HttpUrlConnection
请求。我试图搜索所有这些条款,但我没有得到我需要的东西。在这种情况下,如何按顺序或模式使用它们?将这三种组合使用的任何简单例子都会很棒。还有什么应该是外行人的所有这3个?感谢
InputStream
用于一次一个字节地从Web服务器(或url)读取基于字节的数据。BufferReader
它用于从输入流中一次性读取数据 StringBuffer
用于创建字符串的可修改字符序列,其中所有访问都是同步的。这个类大部分已被StringBuilder取代,因为这种同步很少有用。此类主要用于与公开它的旧API进行交互。 [不明白这意味着什么,因为我的官方语言不是英语]
//These two need to be declared outside the try/catch
//so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
//Construct the URL for the OpenWeatherMap query
//Possible parameters are avaiable at OWM's forecast API page, at
//http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
//Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
//Nothing to do.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
//Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
//But it does make debugging a *lot* easier if you print out the completed
//buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
//Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
//If the code didn't successfully get the weather data, there's no point in attemping
//to parse it.
forecastJsonStr = null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}