List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java
private Bitmap getImageBitmap(String url) { Bitmap bm = null;//from ww w . j a va 2 s.co m try { URL aURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) aURL.openConnection(); long ifs = 0; ifs = conn.getContentLength(); if (ifs == -1) { conn.disconnect(); conn = (HttpURLConnection) aURL.openConnection(); ifs = conn.getContentLength(); } vArtExists = false; if (ifs > 0) { conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); vArtExists = true; //Log.d("EMD - ","art exists - Hurray!"); } else { Log.e("EMD - ", "art fail ifs 0 " + ifs + " " + url); } } catch (IOException e) { vArtExists = false; Log.e("EMD - ", "art fail"); } return bm; }
From source file:com.esminis.server.library.service.server.installpackage.InstallerPackage.java
private void download(Context context, com.esminis.server.library.model.InstallPackage model, File fileOutput) throws Throwable { sendBroadcast(context, STATE_DOWNLOAD, 0); final HttpURLConnection connection = (HttpURLConnection) new URL(model.uri).openConnection(); connection.setConnectTimeout(20000); connection.setReadTimeout(10000);/*from w ww .ja va 2s . co m*/ FileOutputStream output = null; try { output = new FileOutputStream(fileOutput); InputStream inputStream = connection.getInputStream(); final float fileSize = (float) connection.getContentLength(); byte[] buffer = new byte[1024 * 128]; long count = 0; int n; long time = System.currentTimeMillis(); while (-1 != (n = inputStream.read(buffer))) { count += n; output.write(buffer, 0, n); if (System.currentTimeMillis() - time >= 1000) { sendBroadcast(context, STATE_DOWNLOAD, (((float) count) / fileSize) * 0.99f); time = System.currentTimeMillis(); } } sendBroadcast(context, STATE_DOWNLOAD, 0.99f); } finally { connection.disconnect(); if (output != null) { try { output.close(); } catch (IOException ignored) { } } } if (model.hash != null && !model.hash.equals(Utils.hash(fileOutput))) { throw new Exception("Downloaded file was corrupted: " + model.uri); } sendBroadcast(context, STATE_DOWNLOAD, 1); }
From source file:ufms.br.com.ufmsapp.task.DownloadTask.java
@Override protected String doInBackground(String... sUrl) { InputStream input = null;/*from w w w . j a va 2 s . c o m*/ OutputStream output = null; HttpURLConnection connection = null; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); } int fileLength = connection.getContentLength(); input = connection.getInputStream(); output = new FileOutputStream(new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { if (isCancelled()) { input.close(); return null; } total += count; if (fileLength > 0) publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } } catch (Exception e) { return e.toString(); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return null; }
From source file:com.adaptris.core.http.JdkHttpProducer.java
private void readResponse(HttpURLConnection http, AdaptrisMessage reply) throws IOException, CoreException { int responseCode = http.getResponseCode(); logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet()); log.trace("Content-Length is " + http.getContentLength()); if (responseCode < 200 || responseCode > 299) { if (ignoreServerResponseCode()) { log.trace("Ignoring HTTP Reponse code {}", responseCode); processErrorReply(http, reply); return; } else {//from w ww . j a v a 2 s .com throw new ProduceException("Failed to send payload, got " + responseCode); } } if (getEncoder() != null) { copy(getEncoder().readMessage(http), reply); } else { processReply(http, reply); } }
From source file:com.download.cache.image.UrlImageDownloader.java
@Override protected Bitmap download(String key, WeakReference<ImageView> imageViewRef) { URL url;/*from w ww .j a va2 s .c om*/ try { url = new URL(key); } catch (MalformedURLException e) { Log.e(TAG, "url is malformed: " + key, e); return null; } HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Log.e(TAG, "error while opening connection", e); return null; } Bitmap bitmap = null; InputStream httpStream = null; int contentLength; int bytesDownloaded = 0; try { contentLength = urlConnection.getContentLength(); if (contentLength != -1) { httpStream = new FlushedInputStream(urlConnection.getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE); byte[] buffer = new byte[BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE]; while (!isCancelled(imageViewRef)) { int incrementalRead = httpStream.read(buffer); if (incrementalRead == -1) { break; } bytesDownloaded += incrementalRead; if (contentLength > 0 || (bytesDownloaded > 0 && bytesDownloaded == contentLength)) { int progress = bytesDownloaded * 100 / contentLength; publishProgress(progress, imageViewRef); } baf.append(buffer, 0, incrementalRead); } if (isCancelled(imageViewRef)) return null; bitmap = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length()); } else { // steam // byte[] imageBuf; // byte[] buf = new byte[BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE]; // int bufferLeft = buf.length; // int offset = 0; // int result = 0; // // BufferedInputStream bis = new BufferedInputStream(url.openStream()); // // InputStream is = url.openStream(); // outer: do { // while (bufferLeft > 0) { // result = is.read(buf, offset, bufferLeft); // if (result < 0) { // // we're done // break outer; // } // offset += result; // bufferLeft -= result; // } // // resize // bufferLeft = BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE; // int newSize = buf.length + BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE; // byte[] newBuf = new byte[newSize]; // System.arraycopy(buf, 0, newBuf, 0, buf.length); // buf = newBuf; // } while (true); // imageBuf = new byte[offset]; // System.arraycopy(buf, 0, imageBuf, 0, offset); // // bitmap = BitmapFactory.decodeByteArray(imageBuf, 0, imageBuf.length); } } catch (IOException e) { Log.e(TAG, "error creating InputStream", e); } finally { if (urlConnection != null) urlConnection.disconnect(); if (httpStream != null) { try { httpStream.close(); } catch (IOException e) { Log.e(TAG, "IOException while closing http stream", e); } } } return bitmap; }
From source file:IntergrationTest.OCSPIntegrationTest.java
private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception { InputStream is = null;// www . ja va2 s .co m InputStream is_temp = null; try { if (uri == null) return null; URL url = uri.toURL(); if (bActiveCheckUnknownHost) { url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) port = url.getDefaultPort(); InetSocketAddress isa = new InetSocketAddress(host, port); if (isa.isUnresolved()) { //fix JNLP popup error issue throw new UnknownHostException("Host Unknown:" + isa.toString()); } } HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoInput(true); uc.setAllowUserInteraction(false); uc.setInstanceFollowRedirects(true); setTimeout(uc); String contentEncoding = uc.getContentEncoding(); int len = uc.getContentLength(); // is = uc.getInputStream(); if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) { is_temp = uc.getInputStream(); is = new GZIPInputStream(is_temp); } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) { is_temp = uc.getInputStream(); is = new InflaterInputStream(is_temp); } else { is = uc.getInputStream(); } if (len != -1) { int ch, i = 0; byte[] res = new byte[len]; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); } return res; } else { ArrayList<byte[]> buffer = new ArrayList<>(); int buf_len = 1024; byte[] res = new byte[buf_len]; int ch, i = 0; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); if (i == buf_len) { //rotate buffer.add(res); i = 0; res = new byte[buf_len]; } } int total_len = buffer.size() * buf_len + i; byte[] buf = new byte[total_len]; for (int j = 0; j < buffer.size(); j++) { System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len); } if (i > 0) { System.arraycopy(res, 0, buf, buffer.size() * buf_len, i); } return buf; } } catch (Exception e) { e.printStackTrace(); return null; } finally { closeInputStream(is_temp); closeInputStream(is); } }
From source file:org.jvnet.hudson.plugins.m2release.nexus.StageClient.java
private void drainOutput(HttpURLConnection conn) throws IOException { // for things like unauthorised (401) we won't have any content and getting the inputStream will // cause an IOException as we are in error - but there is no really way to tell this so check the // length instead. if (conn.getContentLength() > 0) { if (conn.getErrorStream() != null) { IOUtils.skip(conn.getErrorStream(), conn.getContentLength()); } else {/*from ww w. j a va 2 s .co m*/ IOUtils.skip(conn.getInputStream(), conn.getContentLength()); } } }
From source file:com.baidu.jprotobuf.rpc.client.HttpRPCServerTest.java
/** * @param connection/*from w ww. java2 s .co m*/ * @return */ private byte[] readResponse(HttpURLConnection connection) { InputStream in = null; HttpURLConnection httpconnection = (HttpURLConnection) connection; byte[] resBytes; try { if (httpconnection.getResponseCode() == 200) { in = httpconnection.getInputStream(); } else if ((httpconnection.getErrorStream() != null)) { in = httpconnection.getErrorStream(); } else { in = httpconnection.getInputStream(); } int len = httpconnection.getContentLength(); if (len <= 0) { throw new RuntimeException("no response to get."); } resBytes = new byte[len]; int offset = 0; while (offset < resBytes.length) { int bytesRead = in.read(resBytes, offset, resBytes.length - offset); if (bytesRead == -1) break; offset += bytesRead; } if (offset <= 0) { throw new RuntimeException("there is no service to "); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } return resBytes; }
From source file:org.linphone.tools.OpenH264DownloadHelper.java
/** * Try to download and load codec//from ww w . j ava 2 s . c om * Requirements : * fileDirection * nameFileDownload * urlDownload * nameLib * codecDownListener */ public void downloadCodec() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { String path = fileDirection + "/" + nameLib; URL url = new URL(urlDownload); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); Log.i("OpenH264Downloader", " "); InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream( fileDirection + "/" + nameFileDownload); int totalSize = urlConnection.getContentLength(); openH264DownloadHelperListener.OnProgress(0, totalSize); Log.i("OpenH264Downloader", " Download file:" + nameFileDownload); byte[] buffer = new byte[4096]; int bufferLength; int total = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { total += bufferLength; fileOutputStream.write(buffer, 0, bufferLength); openH264DownloadHelperListener.OnProgress(total, totalSize); } fileOutputStream.close(); inputStream.close(); Log.i("OpenH264Downloader", " Uncompress file:" + nameFileDownload); FileInputStream in = new FileInputStream(fileDirection + "/" + nameFileDownload); FileOutputStream out = new FileOutputStream(path); BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in); while ((bufferLength = bzIn.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); } in.close(); out.close(); bzIn.close(); Log.i("OpenH264Downloader", " Remove file:" + nameFileDownload); new File(fileDirection + "/" + nameFileDownload).delete(); Log.i("OpenH264Downloader", " Loading plugin:" + path); System.load(path); openH264DownloadHelperListener.OnProgress(2, 1); } catch (FileNotFoundException e) { openH264DownloadHelperListener.OnError(e.getLocalizedMessage()); } catch (IOException e) { openH264DownloadHelperListener.OnError(e.getLocalizedMessage()); } } }); thread.start(); }
From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java
private void handleResponse(HttpURLConnection http, AdaptrisMessage reply) throws IOException, InterlokException { int responseCode = http.getResponseCode(); logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet()); log.trace("Content-Length is " + http.getContentLength()); if (responseCode < 200 || responseCode > 299) { if (ignoreServerResponseCode()) { log.trace("Ignoring HTTP Reponse code {}", responseCode); responseBody().insert(new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)), reply);//from w w w . j a v a 2 s .co m } else { fail(responseCode, new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http))); } } else { if (getEncoder() != null) { AdaptrisMessage decodedReply = getEncoder().readMessage(http); AdaptrisMessageImp.copyPayload(decodedReply, reply); reply.getObjectHeaders().putAll(decodedReply.getObjectHeaders()); reply.setMetadata(decodedReply.getMetadata()); } else { responseBody().insert(new InputStreamWithEncoding(http.getInputStream(), getContentEncoding(http)), reply); } } getResponseHeaderHandler().handle(http, reply); reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE, String.valueOf(http.getResponseCode()))); reply.addObjectHeader(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE, Integer.valueOf(http.getResponseCode())); }