List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:com.andreadec.musicplayer.PodcastEpisodeDownloaderService.java
@Override protected void onHandleIntent(Intent intent) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(STOP_DOWNLOAD_INTENT); BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override//from w w w .j a v a2s . c o m public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(STOP_DOWNLOAD_INTENT)) { downloadInProgress = false; } } }; registerReceiver(broadcastReceiver, intentFilter); String type = intent.getStringExtra("type"); String title = intent.getStringExtra("title"); String idItem = intent.getStringExtra("idItem"); String podcastsDirectory = intent.getStringExtra("podcastsDirectory"); notificationBuilder.setContentTitle(getResources().getString(R.string.podcastDownloading, title)); notificationBuilder.setContentText(getResources().getString(R.string.podcastDownloading, title)); notificationManager.notify(Constants.NOTIFICATION_PODCAST_ITEM_DOWNLOAD_ONGOING, notificationBuilder.build()); String filename; do { filename = podcastsDirectory + "/" + UUID.randomUUID().toString(); } while (new File(filename).exists()); // To avoid accidentally override an already existing file Intent intentCompleted = new Intent("com.andreadec.musicplayer.podcastdownloadcompleted"); HttpURLConnection httpConnection = null; try { if (type.equalsIgnoreCase("audio/mpeg") || type.equalsIgnoreCase("audio/.mp3")) filename += ".mp3"; else if (type.equalsIgnoreCase("audio/ogg")) filename += ".ogg"; else throw new Exception("Unsupported format"); URL url = new URL(intent.getStringExtra("url")); httpConnection = (HttpURLConnection) url.openConnection(); if (httpConnection.getResponseCode() != 200) throw new Exception("Failed to connect"); length = httpConnection.getContentLength(); lengthString = Utils.formatFileSize(length); input = httpConnection.getInputStream(); output = new FileOutputStream(filename); byte[] buffer = new byte[1024]; int read = 0; totalRead = 0; downloadInProgress = true; new NotificationThread().start(); while ((read = input.read(buffer)) > 0) { if (!downloadInProgress) { input.close(); throw new Exception(); } output.write(buffer, 0, read); totalRead += read; } intentCompleted.putExtra("success", true); PodcastEpisode.setDownloadedFile(idItem, filename); output.flush(); output.close(); } catch (Exception e) { new File(filename).delete(); PodcastEpisode.setDownloadCanceled(idItem); intentCompleted.putExtra("success", false); intentCompleted.putExtra("reason", e.getMessage()); showErrorNotification(e.getMessage()); } finally { try { httpConnection.disconnect(); } catch (Exception e) { } } downloadInProgress = false; unregisterReceiver(broadcastReceiver); sendBroadcast(intentCompleted); notificationManager.cancel(Constants.NOTIFICATION_PODCAST_ITEM_DOWNLOAD_ONGOING); }
From source file:net.technicpack.launchercore.util.Download.java
@Override @SuppressWarnings("unused") public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;/*from w ww .j a v a 2 s .com*/ try { HttpURLConnection conn = Utils.openHttpConnection(url); int response = conn.getResponseCode(); int responseFamily = response / 100; if (responseFamily == 3) { throw new DownloadException( "The server issued a redirect response which Technic failed to follow."); } else if (responseFamily != 2) { throw new DownloadException("The server issued a " + response + " response code."); } InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); if (size > 0) { if (size == outFile.length()) { result = Result.SUCCESS; } } else { result = Result.SUCCESS; } } catch (PermissionDeniedException e) { exception = e; result = Result.PERMISSION_DENIED; } catch (DownloadException e) { exception = e; result = Result.FAILURE; } catch (Exception e) { exception = e; e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } }
From source file:com.eryansky.common.web.servlet.RemoteContentServlet.java
private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection(); // Socket// ww w . j a v a 2 s. c o m connection.setReadTimeout(TIMEOUT_SECONDS * 1000); try { connection.connect(); // ? InputStream input; try { input = connection.getInputStream(); } catch (FileNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found."); return; } // Header response.setContentType(connection.getContentType()); if (connection.getContentLength() > 0) { response.setContentLength(connection.getContentLength()); } // OutputStream output = response.getOutputStream(); try { // byte?InputStreamOutputStream, ?4k. IOUtils.copy(input, output); output.flush(); } finally { // ??InputStream. IOUtils.closeQuietly(input); } } finally { connection.disconnect(); } }
From source file:com.hmsoft.libcommon.gopro.GoProController.java
public byte[] getImgThumbnail(String fileName) { byte[] fromCache = getImgThumbnailFromCache(mThumbnailCacheDirectory, fileName); if (fromCache != null) return fromCache; long start = 0; if (DEBUG)// ww w. ja v a 2 s . c o m start = System.currentTimeMillis(); HttpURLConnection connection = getMediaConnection(GP_PATH, "gpMediaMetadata", fileName); if (connection == null) return null; try { InputStream in = connection.getInputStream(); int cl = connection.getContentLength(); if (cl <= 0) cl = 512; ByteArrayOutputStream os = new ByteArrayOutputStream(cl); byte[] buffer = new byte[cl]; int i; while ((i = in.read(buffer)) > -1) { os.write(buffer, 0, i); } byte[] thumb = os.toByteArray(); if (Logger.DEBUG) Logger.debug(TAG, "Got %s from camera", fileName); if (DEBUG) { long time = System.currentTimeMillis() - start; Logger.debug(TAG, "getLastImgThumbnail handled in %ds (%d)", time / 1000, time); } saveThumbnailToCache(mThumbnailCacheDirectory, fileName, thumb); return thumb; } catch (IOException e) { Logger.warning(TAG, "Failed to get thumbnail"); } finally { connection.disconnect(); } return null; }
From source file:at.ac.tuwien.qse.sepm.service.impl.FlickrServiceImpl.java
/** * Downloads a photo from a given url/*from w w w .j a v a 2 s . com*/ * * @param url the url of the photo * @param filename the filename of the photo * @param format the format of the photo * @throws ServiceException if the photo can't be downloaded. */ public void downloadTempPhoto(String url, String filename, String format) throws ServiceException { if (filename == null || filename.trim().isEmpty() || format == null || format.trim().isEmpty()) { throw new ServiceException("Photo id or format invalid."); } HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) (new URL(url).openConnection()); } catch (IOException e) { logger.debug(e.getMessage()); throw new ServiceException(e.getMessage(), e); } try (BufferedInputStream in = new BufferedInputStream((httpConnection.getInputStream())); FileOutputStream fout = new FileOutputStream( Paths.get(tmpDir, filename + "." + format).toString())) { long completeFileSize = httpConnection.getContentLength(); logger.debug("Size of the photo is {} MB", (double) completeFileSize / oneMB); final byte data[] = new byte[1024]; int count; long downloadedFileSize = 0; while ((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); downloadedFileSize = downloadedFileSize + count; // maybe produces too much output // logger.debug("Downloaded {} MB", (double)downloadedFileSize/oneMB); } logger.debug("Downloaded photo {}", filename + "." + format); new File(Paths.get(tmpDir, filename + "." + format).toString()).deleteOnExit(); } catch (IOException e) { logger.debug(e.getMessage()); throw new ServiceException(e.getMessage(), e); } }
From source file:com.commonsware.android.EMusicDownloader.SingleBook.java
private Bitmap getImageBitmap(String url) { Bitmap bm = null;//from w w w .j a v a 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; } } catch (IOException e) { vArtExists = false; final IOException ef = e; final String urlf = url; } return bm; }
From source file:com.bigstep.datalake.DLFileSystem.java
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream) throws IOException { if (c.getContentLength() == 0) { return null; }//from ww w . java2s. c o m final InputStream in = useErrorStream ? c.getErrorStream() : c.getInputStream(); if (in == null) { throw new IOException("The " + (useErrorStream ? "error" : "input") + " stream is null."); } try { final String contentType = c.getContentType(); if (contentType != null) { final MediaType parsed = MediaType.valueOf(contentType); if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) { throw new IOException("Content-Type \"" + contentType + "\" is incompatible with \"" + MediaType.APPLICATION_JSON + "\" (parsed=\"" + parsed + "\")"); } } final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Gson gson = new Gson(); return gson.fromJson(reader, Map.class); } finally { in.close(); } }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public double testDownload() { double bw = 0.0; try {/*www. j ava 2 s. com*/ Date oldTime = new Date(); URL obj = new URL(amazonDomain + "/download_test.bin"); HttpURLConnection httpGetCon = (HttpURLConnection) obj.openConnection(); // optional default is GET httpGetCon.setRequestMethod("GET"); httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds httpGetCon.setReadTimeout(5000); //add request header httpGetCon.setRequestProperty("User-Agent", USER_AGENT); if (httpGetCon.getResponseCode() == 200) { Date newTime = new Date(); double milliseconds = newTime.getTime() - oldTime.getTime(); int lenght = httpGetCon.getContentLength(); bw = ((double) lenght * 8) / (milliseconds * (double) 1000); } // BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); // String inputLine; // StringBuffer response = new StringBuffer(); // while ((inputLine = in.readLine()) != null) { // response.append(inputLine); // } // in.close(); // // //print result // System.out.println(response.toString()); } catch (MalformedURLException e) { System.out.println("MalformedURLException is fired!"); } catch (IOException e) { System.out.println("Exception is fired in download test. error:" + e.getMessage()); } return bw; }
From source file:edu.cmu.cs.quiltview.RequestPullingService.java
private void pullRequest() { String resultTxt = " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis()); Log.i(LOG_TAG, "Begin pull." + resultTxt); getLocation();//from ww w. ja v a2 s . co m double latitude, longitude; if (mLocation != null) { Log.i(LOG_TAG, "Real Location"); latitude = mLocation.getLatitude(); longitude = mLocation.getLongitude(); } else { //TODO test real location /* * As we usually develop and demo indoor, the GPS location is not always * available. For the convenience of development, we use theses fixed fake * location. This is somewhere on Carnegie Mellon University campus * Wenlu Hu, April 2014 */ Log.i(LOG_TAG, "Fake Location"); latitude = 40.443469; //40.44416720; longitude = -79.943862; //-79.94336060; } Log.i(LOG_TAG, "Location: " + latitude + ", " + longitude); HttpURLConnection urlConnection = null; try { URL url = new URL(Const.quiltview_server_addr + "/latest/" + "?user_id=" + mSerialNumber + "&lat=" + latitude + "&lng=" + longitude); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Content-Type", "application/json"); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = urlConnection.getInputStream(); int responseLen = urlConnection.getContentLength(); Log.i(LOG_TAG, "Response Len = " + responseLen); //Read the json file byte[] jsonBuffer = new byte[responseLen]; Log.i(LOG_TAG, "Response Len = " + is.read(jsonBuffer)); String jsonString = new String(jsonBuffer, "UTF-8"); Log.i(LOG_TAG, "Got response: " + jsonString); try { JSONObject obj = (JSONObject) JSONValue.parse(jsonString); String query = obj.get("content").toString(); int queryID = Integer.parseInt(obj.get("query_id").toString()); int userID = Integer.parseInt(obj.get("user_id").toString()); String imagePath = obj.get("image").toString(); Log.i(LOG_TAG, userID + ", " + queryID + ": " + query + "&" + imagePath); imagePath = saveImageToLocal(imagePath); recordForQuery(query, queryID, userID, imagePath); } catch (NullPointerException ex) { Log.i(LOG_TAG, "No valid query"); } } else { Log.e(LOG_TAG, "Response " + urlConnection.getResponseCode() + ":" + urlConnection.getResponseMessage()); } } catch (MalformedURLException ex) { Log.e(LOG_TAG, "", ex); } catch (IOException ex) { Log.e(LOG_TAG, "", ex); } finally { if (urlConnection != null) urlConnection.disconnect(); } }
From source file:org.digitalcampus.oppia.task.DownloadMediaTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];//from ww w . j a va2 s.c o m for (Object o : payload.getData()) { Media m = (Media) o; File file = new File(MobileLearning.MEDIA_PATH, m.getFilename()); try { URL u = new URL(m.getDownloadUrl()); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); DownloadProgress dp = new DownloadProgress(); dp.setMessage(m.getFilename()); dp.setProgress(0); publishProgress(dp); FileOutputStream f = new FileOutputStream(file); InputStream in = c.getInputStream(); MessageDigest md = MessageDigest.getInstance("MD5"); in = new DigestInputStream(in, md); byte[] buffer = new byte[8192]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); // check the file digest matches, otherwise delete the file // (it's either been a corrupted download or it's the wrong file) byte[] digest = md.digest(); String resultMD5 = ""; for (int i = 0; i < digest.length; i++) { resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); } Log.d(TAG, "supplied digest: " + m.getDigest()); Log.d(TAG, "calculated digest: " + resultMD5); if (!resultMD5.contains(m.getDigest())) { this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } else { payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename())); } } catch (ClientProtocolException e1) { e1.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (IOException e1) { e1.printStackTrace(); this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (NoSuchAlgorithmException e) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(e); } else { e.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } } return payload; }