文件下载的步骤
1 创建一个HttpURLConnection对象
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
2 获得一个InputStream对象 urlConn.getInputStream()
3 访问网络的权限 android.permission.INTERNET
package jianglin.download;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownload {
private URL url = null;
/*
* 根据url下载文,前提是这个文件中的内容是文本,函数的返回值是文件当中的内容
* 1,创建一个URL对象
* 2,通过URL对象,创建一个HttpURLConnectiond对象
* 3,得到InputStream
* 4,从InputStream当中读取数据
*/
public String download(String urlStr){
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try{
//创建一个URL对象
url = new URL(urlStr);
//创建一个Http连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//使用IO读取数据
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = buffer.readLine()) != null){
sb.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
buffer.close();
}catch(Exception e){
e.printStackTrace();
}
}
return sb.toString();
}
}
111