If you think the Android project khandroid listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
/*
* Copyright (C) 2012-2014 Ognyan Bankov
*//www.java2s.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/package com.github.khandroid.http.misc;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.slf4j.LoggerFactory;
import khandroid.ext.apache.http.HttpEntity;
import khandroid.ext.apache.http.HttpResponse;
import khandroid.ext.apache.http.StatusLine;
import khandroid.ext.apache.http.client.ClientProtocolException;
import khandroid.ext.apache.http.client.HttpClient;
import khandroid.ext.apache.http.client.methods.HttpGet;
publicclass FileDownloader {
privatestaticfinal org.slf4j.Logger logger = LoggerFactory
.getLogger(FileDownloader.class.getSimpleName());
publicstaticbyte[] download(HttpClient httpClient, URI source) throws ClientProtocolException,
IOException {
byte[] ret;
logger.trace("Downloading " + source.toString());
HttpGet req = new HttpGet(source);
HttpResponse response = httpClient.execute(req);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
logger.trace("Status code:" + statusCode);
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
ByteArrayOutputStream output = new ByteArrayOutputStream();
entity.writeTo(output);
output.close();
ret = output.toByteArray();
} else {
thrownew IOException("Download failed, HTTP response code " + statusCode + " - "
+ statusLine.getReasonPhrase());
}
req.releaseConnection();
return ret;
}
publicstaticvoid download(HttpClient httpClient, URI source, File destination) throws ClientProtocolException,
IOException {
byte[] content = download(httpClient, source);
ByteArrayInputStream input = new ByteArrayInputStream(content);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(destination));
copy(input, output);
input.close();
output.close();
}
publicstaticlong copy(InputStream from, OutputStream to) throws IOException {
byte[] buf = newbyte[0x1000];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
}