根据url下载文件
public static String downloadFile(String urlsrc, String filename, String filePath, String cookie) {
InputStream in = null;
FileOutputStream out = null;
try{
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,5000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet httpget1 = new HttpGet(urlsrc);
HttpResponse httpResponse1 = client.execute(httpget1);
System.out.println("状态码:"+httpResponse1.getStatusLine().getStatusCode());
if (httpResponse1.getStatusLine().getStatusCode() != 200)
System.out.println("网络错误异常!!!!");
else
System.out.println("网络连接成功!!!");
httpget1.abort();
HttpGet httpget2 = new HttpGet(urlsrc);
if (StringUtils.isNotBlank(cookie)){
httpget2.addHeader("Cookie",cookie);
}
HttpResponse httpResponse2 = client.execute(httpget2);
HttpEntity entity = httpResponse2.getEntity();
in = entity.getContent();
File savePath = new File(filePath);
if (!savePath.exists()) {
boolean mkdir = savePath.mkdirs();
if (!mkdir) {
System.out.println("创建文件夹失败");
}
}
out = new FileOutputStream(new File(filePath + File.separator + filename));
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!= -1){
out.write(b,0,len);
}
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("download, success!!");
return filePath + File.separator + filename;
}
根据url下载图片
private String downloadImg(String imgUrl, String filename, String filePath) {
URL url = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
url = new URL(imgUrl);
URLConnection con = url.openConnection();
con.setConnectTimeout(5 * 1000);
inputStream = con.getInputStream();
byte[] bytes = new byte[1024];
int length;
if (System.getProperty("os.name").toLowerCase().contains("windows")){
}else if (System.getProperty("os.name").toLowerCase().contains("linux")){
}
File savePath = new File(filePath);
if (!savePath.exists()) {
boolean mkdir = savePath.mkdirs();
if (!mkdir) {
System.out.println("创建文件夹失败");
return null;
}
}
outputStream = new FileOutputStream(savePath.getPath() + "\\" + filename);
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return filePath + File.separator + filename;
}