HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream in = con.getInputStream(); 这里空指针异常
代码为开源代码如下
//下载普通纯文本文件
public String download(String urlStr){
String line = null;
StringBuffer sb = new StringBuffer();
BufferedReader bufr = null;
try {
//创建一个URL对象
url = new URL(urlStr);
//创建一个http连接
HttpURLConnection con = (HttpURLConnection)url.openConnection();
//读取文件
bufr = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = bufr.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
System.out.println("文本文件下载失败!");
}finally{
if(bufr!=null)
try {
bufr.close();
} catch (IOException e) {
System.out.println("文本文件读取流关闭失败!");
}
}
return sb.toString();
}
//可下载各种文件
//返回 -1:代表下载文件出错, 返回0:代表下载文件成功,返回 1:代表文件已经存在
//fileName代表你将要存入SD卡中的文件名,可以定义自己的文件名
public int downloadFile(String url,String path,String fileName){
InputStream in = null;
try {
FileUtils utils = new FileUtils() ;
if(utils.isFileExist(path+fileName)){
return 1;
}else{
in = getInputStreamFromUrl(url);
File resultFile = utils.write2SDFromInputStream(path, fileName, in);
if(resultFile == null){
return -1;
}
}
} catch (IOException e) {
e.printStackTrace();
return -1;
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
System.out.println("字节读取流关闭失败!");
}
}
}
return 0;
}
//将根据Url获取InputStream的功能封装起来,以便复用
public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream in = con.getInputStream();
return in;
}
}
URL
------解决方案--------------------
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream in = con.getInputStream(); 这里空指针异常
中间怎么没有
con.connect()
------解决方案--------------------
楼上所言极是,conn.connect();