解决方案 »
- android源码编译问题
- JNI 的 char 转jstring的中文崩溃的问题
- android关于hook驱动----私活
- 请问一个关于源代码编译的问题
- 我用多普达s1的手机内置IE浏览wap网站的时候,提示“该页包含错误,无法显示”
- 怎么实现在一个View类中播放GIF动画?
- android 怎么实现自动点击
- Android 快捷方式 传参
- couldn't load memtrack module (No such file or directory)
- 冰天雪地裸替跪求 android添加系统级库
- 就想显示个图片出来 咋就这么难。实在没有奖励分了。。。。
- 需要做一个IP Carema 的安卓端!~求思路
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;import android.os.Handler;public class HttpDownLoader {
private URL url;
/**
* 读取文本文件,返回字符串
* @param urlStr
* @return
*/
public String download(String urlStr) {
StringBuffer sb=new StringBuffer();
String line=null;
BufferedReader buffer=null;
try {
//创建一个url对象
url=new URL(urlStr);
//创建一个Http连接
HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
urlcon.setRequestMethod("GET"); //使用get请求
//使用IO读取数据
buffer=new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
//循环
while((line=buffer.readLine())!=null){
sb.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if(buffer != null){
buffer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 读取文件,并保存起来
* @param urlStr
* @param path
* @param fileName
* @return -1:下载出错 0:成功 1: 文件已经存在
*/
public int downFile(String urlStr,String path,String fileName,Handler handler){
int result=-1;
InputStream inputStream=null;
FileUtils fileUtils=new FileUtils();
int filesize = 0;
try {
if(fileUtils.isFileExist(path+fileName)){
return 1;
}else{
url=new URL(urlStr);
HttpURLConnection urlCon=(HttpURLConnection)url.openConnection();
inputStream=urlCon.getInputStream();
filesize = urlCon.getContentLength();
File resultFile=fileUtils.write2SDFromInput(path, fileName, inputStream, handler, filesize);
if(resultFile==null){
return -1;
}
}
} catch (IOException e) {
e.printStackTrace();
return -1;
}finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return 0;
}
/**
* 根据url地址获取输入流
* @param urlStr
* @return
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
url=new URL(urlStr);
HttpURLConnection urlCon=(HttpURLConnection)url.openConnection();
InputStream inputStream=urlCon.getInputStream();
return inputStream;
}
}
这个是 我 app中用到的。
android 模拟器 如果你没有设置的话,是不能上网的,你要模拟 器的默认DNS设置成电脑的DNS地址 才能上网。 具体怎么设置 你自己百度 一下吧,网上有设置的。