Android平台有3中网络接口:
- java.net.*;//标准java接口
- org.apache.*;//Apache接口,提供 Apache HttpClient ,比JDK更完善
- android.net.*;//对Apache HttpClient封装
按钮1:从Internet下载一个纯文本文件,然后输出显示在System.in过滤器中
按钮2:下载MP3文件到模拟器的/sdcard/voa/MySoul.mp3
这个是主运行程序
}
class ButtonTxtListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownloader httpDownloader = new HttpDownloader();
String lrc = httpDownloader.download("http://www.hazegray.org/danfs/csn/a.txt");
System.out.println(lrc);
}
}
class ButtonMp3Listener implements OnClickListener {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
HttpDownloader httpDownloader = new HttpDownloader();
httpDownloader.downFile("http://127.0.0.1/android/test.mp3", "music/", "MySoul.mp3");
System.out.println("Success download the Mp3");
}
}
}
HttpDownloader.java
if (fileUtils.isFileExist(path + fileName)) {
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
/**
* 根据URL得到输入流
*
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConn.getInputStream();
return inputStream;
}
}
FileUtils.java,为HttpDownloader.java提供的工具类
/**
* 在SD卡上创建目录
*
* @param dirName
*/
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdir();
return dir;
}
/**
* 判断SD卡上的文件夹是否存在
*/
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 将一个InputStream里面的数据写入到SD卡中
*/
public File write2SDFromInput(String path,String fileName,InputStream input){
File file = null;
OutputStream output = null;
try{
creatSDDir(path);
file = creatSDFile(path + fileName);
output = new FileOutputStream(file);
byte buffer [] = new byte[4 * 1024];
while((input.read(buffer)) != -1){
output.write(buffer);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return file;
}
}
AndroidManifest.xml应加入以下两行,使Application具有访问Internet和SD卡的权限