将网络流转化为String
InputStream inputStream = url.openStream(); // 从URL上取得字节流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = -1;
byte[] buffer = new byte[1024 * 4];
while ((ch = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, ch);
}
baos.flush();
String responseXml = baos.toString(HTTP.UTF_8); // 依据需求可以选择要要的字符编码格式
if (isr != null) { // 打印最后结果
Log.i(TAG, "得到的字符串是:" + responseXml);
}
把网络流直接写入文件
- // 得到读取的内容(流)
- // 使用循环来读取获得的数据,并写入文件
- FileOutputStream outFileStream = m_context.openFileOutput(fileName,
- Context.MODE_PRIVATE);
- InputStream inPutSteam = urlConn.getInputStream();
- byte[] bufferinPut = new byte[4096];
- int lengthinPut = -1;
- while ((lengthinPut = inPutSteam.read(bufferinPut)) != -1) {
- outFileStream.write(bufferinPut,0,lengthinPut);
- }
- //关闭文件流
- inPutSteam.close();
- outFileStream.close();