android利用http协议下载网页内容到指定位置的方法
源码如下:[java]
<span style="font-size:18px">
</span>
[java] view plaincopyprint?
<span style="font-size:18px">public class LoadTestActivity extends Activity {
private TextView tv;
private URL url;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
String urlStr="http://www.eoeandroid.com/thread-108676-1-1.html";
tv.setText(getWebText(urlStr));
//loadToSdcard(urlStr,"/TTTTT","Ada的文件.txt");
loadToLocation(urlStr,"Abc.txt");
}
//初始化组件
public void init(){
tv=(TextView)findViewById(R.id.tv);
}
//获取文件流
private InputStream getInputStream(String urlStr){
InputStream is = null;
try {
url=new URL(urlStr);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.connect();
is=conn.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
//获取网页文本内容
private String getWebText(String urlStr){
InputStream is=getInputStream(urlStr);
StringBuffer sb=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String s="";
try {
while((s=br.readLine())!=null){
sb.append(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("TAG", "流文件读写错误");
}
finally{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sb.toString();
}
//下载文件
private void 易做图(InputStream is,String path,String filename){
String filepath=null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
filepath=Environment.getExternalStorageDirectory()+path;
}
else{
Toast.makeText(LoadTestActivity.this, "SDCard异常,请检查SDCard是否安装正确!", Toast.LENGTH_LONG).show();
}
if(!filepathExist(filepath)){
createFilepath(filepath);
}
if(!fileExist(filepath+"/"+filename)){
createFile(is,filepath,filename);
}
}
//判断文件路径是否存在
private boolean filepathExist(String filepath){
File file=new File(filepath);
return file.exists();
}
//创建文件路径
private void createFilepath(String filepath){
File file=new File(filepath);
file.mkdirs();
}
//判断文件是否存在
private boolean fileExist(String filename){
return filepathExist(filename);
}
//创建文件
private void createFile(InputStream is,String filepath,String filename){
File file=new File(filepath+"/"+filename);
OutputStream os=null;
try {
os=new FileOutputStream(file);
int len=0;
补充:移动开发 , Android ,