[文件] HttpDownloader.java
01
import java.io.BufferedReader;
02
import java.io.File;
03
import java.io.IOException;
04
import java.io.InputStream;
05
import java.io.InputStreamReader;
06
import java.net.HttpURLConnection;
07
import java.net.MalformedURLException;
08
import java.net.URL;
09
10
/***
11
* 通过http协议下载文件
12
* ***/
13
public class HttpDownloader {
14
15
private URL url = null;
16
17
public InputStream getInputStreamFormUrl(String urlStr)
18
throws MalformedURLException,IOException{
19
url = new URL(urlStr);
20
HttpURLConnection httpc = (HttpURLConnection)url.openConnection();
21
return httpc.getInputStream();
22
}
23
24
public String downloadText(String urlStr){
25
StringBuffer sb = new StringBuffer();
26
String line = null;
27
BufferedReader breader = null;
28
try{
29
url = new URL(urlStr);
30
HttpURLConnection httpc = (HttpURLConnection)url.openConnection();
31
InputStream inputs = httpc.getInputStream();
32
breader = new BufferedReader(new InputStreamReader(inputs));
33
while((line=breader.readLine())!=null){
34
sb.append(line);
35
}
36
}catch(Exception e){
37
e.printStackTrace();
38
}finally{
39
try {
40
breader.close();
41
} catch (IOException e) {
42
// TODO Auto-generated catch block
43
e.printStackTrace();
44
}
45
}
46
return sb.toString();
47
}
48
49
public int downloadFile(String urlStr,String path,String name){
50
InputStream input = null;
51
try{
52
FileUtils fu = new FileUtils();
53
if(fu.isFileExist(path+name)){// 是否存在文件,如果存在返回1
54
return 1;
55
}else{
56
input = getInputStreamFormUrl(urlStr);
57
File f = fu.inputStream2File(path, name, input);软件开发
58
if(f==null){
59
return -1;// 数据有异常的时候返回-1
60
}
61
input.close();
62
}
63
}catch(Exception e){
64
e.printStackTrace();
65
return -1;
66
}
67
return 0;// 数据正常的时候返回0
68
}
69
70
}