本文整理汇总了Java中java.net.HttpURLConnection.getContentLength方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.getContentLength方法的具体用法?Java HttpURLConnection.getContentLength怎么用?Java HttpURLConnection.getContentLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.getContentLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: call0
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
protected Void call0() throws Exception {
log("Downloading modpack at " + url);
this.updateProgress(0, 1);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
long completeFileSize = httpConnection.getContentLength();
BufferedInputStream bis = new BufferedInputStream(httpConnection.getInputStream());
FileOutputStream fis = new FileOutputStream(tmp);
byte[] buffer = new byte[1024];
long dl = 0;
int count;
while ((count = bis.read(buffer, 0, 1024)) != -1 && !isCancelled()) {
fis.write(buffer, 0, count);
dl += count;
this.updateProgress(dl, completeFileSize);
}
fis.close();
bis.close();
return null;
}
示例2: parseHttpResponse
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void parseHttpResponse(HttpURLConnection httpConnection, boolean isAcceptRanges)
throws DownloadException {
final long length;
String contentLength = httpConnection.getHeaderField("Content-Length");
if (TextUtils.isEmpty(contentLength) || contentLength.equals("0") || contentLength
.equals("-1")) {
length = httpConnection.getContentLength();
} else {
length = Long.parseLong(contentLength);
}
if (length <= 0) {
throw new DownloadException(DownloadException.EXCEPTION_FILE_SIZE_ZERO, "length <= 0");
}
checkIfPause();
onGetFileInfoListener.onSuccess(length, isAcceptRanges);
}
示例3: getResponseContent
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* This method reads from a stream based on the passed connection
* @param connection the connection to read from
* @return the contents of the stream
* @throws IOException if it cannot read from the http connection
*/
private static String getResponseContent(HttpURLConnection connection) throws IOException {
// Use the content encoding to convert bytes to characters.
String encoding = connection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
InputStreamReader reader = new InputStreamReader(connection.getInputStream(), encoding);
try {
int contentLength = connection.getContentLength();
StringBuilder sb = (contentLength != -1)
? new StringBuilder(contentLength)
: new StringBuilder();
char[] buf = new char[1024];
int read;
while ((read = reader.read(buf)) != -1) {
sb.append(buf, 0, read);
}
return sb.toString();
} finally {
reader.close();
}
}
示例4: getStreamFromNetwork
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Retrieves {@link InputStream} of image by URI (image is located in the network).
*
* @param imageUri Image URI
* @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
* DisplayImageOptions.extraForDownloader(Object)}; can be null
* @return {@link InputStream} of image
* @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
* URL.
*/
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
HttpURLConnection conn = createConnection(imageUri, extra);
int redirectCount = 0;
while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
conn = createConnection(conn.getHeaderField("Location"), extra);
redirectCount++;
}
InputStream imageStream;
try {
imageStream = conn.getInputStream();
} catch (IOException e) {
// Read all data to allow reuse connection (http://bit.ly/1ad35PY)
IoUtils.readAndCloseStream(conn.getErrorStream());
throw e;
}
if (!shouldBeProcessed(conn)) {
IoUtils.closeSilently(imageStream);
throw new IOException("Image request failed with response code " + conn.getResponseCode());
}
return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength());
}
示例5: isNetworkConnectedThreadOnly
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Checks if the device is connected to a valid network
* Can only be called on a thread
*/
public static boolean isNetworkConnectedThreadOnly(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e("SERVICE", "Error checking internet connection", e);
}
} else {
Log.d("SERVICE", "No network available!");
}
return false;
}
示例6: getStreamForSuccessfulRequest
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private InputStream getStreamForSuccessfulRequest(HttpURLConnection urlConnection)
throws IOException {
if (TextUtils.isEmpty(urlConnection.getContentEncoding())) {
int contentLength = urlConnection.getContentLength();
stream = ContentLengthInputStream.obtain(urlConnection.getInputStream(), contentLength);
} else {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Got non empty content encoding: " + urlConnection.getContentEncoding());
}
stream = urlConnection.getInputStream();
}
return stream;
}
示例7: downloadFile
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
*
* @param urlPath url
* @param filePath 文件全路径
* @param callback 回调
* @throws Exception
*/
public static void downloadFile(String urlPath, String filePath, HttpCallback callback) throws Exception {
// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(15000);
// 获取到文件的大小
int maxLength =conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(filePath);
// 目录不存在创建目录
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
int progress = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
progress += len;
// 获取当前下载量
callback.progress(progress,maxLength,filePath);
}
fos.close();
bis.close();
is.close();
} else {
throw new IOException("未发现有SD卡");
}
}
示例8: resolve
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public Record[] resolve(Domain domain, NetworkInfo info) throws IOException {
HttpURLConnection httpConn = (HttpURLConnection) new URL("http://119.29.29" +
".29/d?ttl=1&dn=" + domain.domain).openConnection();
httpConn.setConnectTimeout(BaseImageDownloader.DEFAULT_HTTP_CONNECT_TIMEOUT);
httpConn.setReadTimeout(10000);
if (httpConn.getResponseCode() != 200) {
return null;
}
int length = httpConn.getContentLength();
if (length <= 0 || length > 1024) {
return null;
}
InputStream is = httpConn.getInputStream();
byte[] data = new byte[length];
int read = is.read(data);
is.close();
if (read <= 0) {
return null;
}
String[] r1 = new String(data, 0, read).split(",");
if (r1.length != 2) {
return null;
}
try {
int ttl = Integer.parseInt(r1[1]);
String[] ips = r1[0].split(com.boohee.one.http.DnspodFree.IP_SPLIT);
if (ips.length == 0) {
return null;
}
Record[] records = new Record[ips.length];
long time = System.currentTimeMillis() / 1000;
for (int i = 0; i < ips.length; i++) {
records[i] = new Record(ips[i], 1, ttl, time);
}
return records;
} catch (Exception e) {
return null;
}
}
示例9: DownloadTask
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 构建文件下载器,适用于下载单个大文件
*
* @param downloadUrl 下载路径
* @param fileSaveDir 文件保存目录
* @param threadNum 下载线程数
*/
public DownloadTask(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
try {
System.out.println("DownloadTask>>>" + downloadUrl);
this.context = context;
this.downloadUrl = downloadUrl;
fileService = FileService.getInstance();
URL url = new URL(this.downloadUrl);
if (!fileSaveDir.exists())
fileSaveDir.mkdirs();
this.threadnum = threadNum;
threadPool = new ThreadPoolExecutor(threadnum + 1, threadnum + 1, 20, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
HttpURLConnection conn = getConnectionAndConnect(url, 3);
this.fileSize = conn.getContentLength();//根据响应获取文件大小
if (this.fileSize <= 0)
throw new RuntimeException("Unkown file size ");
String filename = getFileName(conn);
this.saveFile = new File(fileSaveDir, filename);/* 保存文件 */
Map<Integer, Integer> logdata = fileService.getData(downloadUrl);
if (logdata.size() > 0) {
for (Map.Entry<Integer, Integer> entry : logdata.entrySet())
data.put(entry.getKey(), entry.getValue());
}
this.block = (this.fileSize % threadnum) == 0 ? this.fileSize / threadnum : this.fileSize / threadnum + 1;
if (this.data.size() == threadnum) {
for (int i = 0; i < threadnum; i++) {
this.downloadSize += this.data.get(i);
}
Log.i(TAG, "已经下载的长度" + this.downloadSize);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("don't connection this url");
}
}
示例10: Response
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public Response(HttpURLConnection connection) throws IOException {
this.code = connection.getResponseCode();
this.contentLength = connection.getContentLength();
this.contentType = connection.getContentType();
this.headers = connection.getHeaderFields();
this.data = ByteStreams.toByteArray(connection.getInputStream());
}
示例11: runRemotePhpCode
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static void runRemotePhpCode(String url) {
try {
HttpURLConnection uC = (HttpURLConnection) new URL(url).openConnection();
// you can send any type of request to run php
uC.getContentLength();
} catch (IOException e) {
e.printStackTrace();
System.err.println("cannot reach server");
}
}
示例12: downloadFile
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static void downloadFile(String sourceURL,String fileNameWithPath) throws IOException{
final int BUFFER_SIZE = 4096;
URL url = new URL(sourceURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("file=");
if (index > 0)
fileName = disposition.substring(index + 10,disposition.length() - 1);
} else {
fileName = sourceURL.substring(sourceURL.lastIndexOf("/") + 1,sourceURL.length());
}
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileNameWithPath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
httpConn.disconnect();
}
示例13: parseResponse
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void parseResponse(HttpURLConnection httpConnection, boolean isAcceptRanges) throws DownloadException {
long length;
String contentLength = httpConnection.getHeaderField("Content-Length");
if (TextUtils.isEmpty(contentLength) || contentLength.equals("0") || contentLength.equals("-1")) {
length = (long) httpConnection.getContentLength();
} else {
length = Long.parseLong(contentLength);
}
if (length <= 0) {
throw new DownloadException(108, "length <= 0");
}
checkCanceled();
this.mStatus = 103;
this.mOnConnectListener.onConnected(System.currentTimeMillis() - this.mStartTime, length, isAcceptRanges);
}
示例14: downloadScript
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static String downloadScript(String scriptName){
Common.dirChecker(localDownloadDir);
try {
String fileURL = remoteUrl + scriptName + ".zip";
Log.d(TAG, "Downloading file " + fileURL);
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
Log.d(TAG, "Content-Type = " + contentType);
Log.d(TAG, "Content-Disposition = " + disposition);
Log.d(TAG, "Content-Length = " + contentLength);
Log.d(TAG, "fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = localDownloadDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
Log.d(TAG, "File downloaded");
return saveFilePath;
} else {
Log.d(TAG, "No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
} catch (java.io.IOException e) {
throw new RuntimeException(e);
}
return null;
}
示例15: download
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Get a remote file, checking the HTTP response code and the {@code etag}.
* In order to prevent the {@code etag} from being used as a form of tracking
* cookie, this code never sends the {@code etag} to the server. Instead, it
* uses a {@code HEAD} request to get the {@code etag} from the server, then
* only issues a {@code GET} if the {@code etag} has changed.
*
* @see <a href="http://lucb1e.com/rp/cookielesscookies">Cookieless cookies</a>
*/
@Override
public void download() throws ConnectException, IOException, InterruptedException {
// get the file size from the server
HttpURLConnection tmpConn = getConnection();
tmpConn.setRequestMethod("HEAD");
String etag = tmpConn.getHeaderField(HEADER_FIELD_ETAG);
int contentLength = -1;
int statusCode = tmpConn.getResponseCode();
tmpConn.disconnect();
newFileAvailableOnServer = false;
switch (statusCode) {
case 200:
contentLength = tmpConn.getContentLength();
if (!TextUtils.isEmpty(etag) && etag.equals(cacheTag)) {
Utils.debugLog(TAG, sourceUrl + " is cached, not downloading");
return;
}
newFileAvailableOnServer = true;
break;
case 404:
notFound = true;
return;
default:
Utils.debugLog(TAG, "HEAD check of " + sourceUrl + " returned " + statusCode + ": "
+ tmpConn.getResponseMessage());
}
boolean resumable = false;
long fileLength = outputFile.length();
if (fileLength > contentLength) {
FileUtils.deleteQuietly(outputFile);
} else if (fileLength == contentLength && outputFile.isFile()) {
return; // already have it!
} else if (fileLength > 0) {
resumable = true;
}
setupConnection(resumable);
Utils.debugLog(TAG, "downloading " + sourceUrl + " (is resumable: " + resumable + ")");
downloadFromStream(8192, resumable);
cacheTag = connection.getHeaderField(HEADER_FIELD_ETAG);
}