List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:com.micro.utils.F.java
/** * ????.//from w ww .j a v a 2 s . c o m * * @param Url * @return int ? */ public static int getContentLengthFromUrl(String Url) { int mContentLength = 0; try { URL url = new URL(Url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", Url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { // ???? mContentLength = mHttpURLConnection.getContentLength(); } } catch (Exception e) { e.printStackTrace(); L.D("?" + e.getMessage()); } return mContentLength; }
From source file:com.online.fullsail.SaveWebMedia.java
@Override protected File doInBackground(String... paths) { String exportfile = paths[0].substring(paths[0].lastIndexOf('/') + 1, paths[0].length()); String vDownload = externalData + "/" + exportfile; File downFile = null;//from w w w . java 2 s.c o m try { // set the download URL of the file to be downloaded URL url = new URL(paths[0]); // create the new connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Connection", "Keep-Alive"); // and connect! urlConnection.connect(); // set the path where we want to save the file File SDCardRoot = Environment.getExternalStorageDirectory(); // create a new file, with specified path and name downFile = new File(SDCardRoot, vDownload); // this will be used to write the downloaded data // into the file // we created FileOutputStream fileOutput = new FileOutputStream(downFile); // this will be used in reading the data from the // internet InputStream inputStream = urlConnection.getInputStream(); // this is the total size of the file int totalSize = urlConnection.getContentLength(); // variable to store total downloaded bytes int downloadedSize = 0; // create a buffer... byte[] buffer = new byte[1024]; int bufferLength = 0; // used to store a temporary buffer then // read through the input buffer and write // to the specified output file int priorProgress = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { downloadedSize += bufferLength; int currentSize = (int) (downloadedSize * 100 / totalSize); if (currentSize > priorProgress) { priorProgress = (int) (downloadedSize * 100 / totalSize); publishProgress(currentSize); } fileOutput.write(buffer, 0, bufferLength); } // close the output stream when done fileOutput.close(); inputStream.close(); // catch some possible errors... } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return downFile; // When finished, return the resulting file }
From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncGetAlbumArtTask.java
@Override protected Integer doInBackground(String... params) { /************************************************************************************************ * RETRIEVE THE HTTP SEARCH RESPONSE FROM ITUNES SERVERS. ************************************************************************************************/ //First, we'll make a HTTP request to iTunes' servers with the album and artist name. if (params.length == 2) { artist = params[0];//from w w w.j a va 2s .co m album = params[1]; //Create duplicate strings that will be filtered out for the URL. urlArtist = artist; urlAlbum = album; //Remove any unacceptable characters. if (urlArtist.contains("#")) { urlArtist = urlArtist.replace("#", ""); } if (urlArtist.contains("$")) { urlArtist = urlArtist.replace("$", ""); } if (urlArtist.contains("@")) { urlArtist = urlArtist.replace("@", ""); } if (urlAlbum.contains("#")) { urlAlbum = urlAlbum.replace("#", ""); } if (urlAlbum.contains("$")) { urlAlbum = urlAlbum.replace("$", ""); } if (urlAlbum.contains("@")) { urlAlbum = urlAlbum.replace("@", ""); } //Replace any spaces in the artist and album fields with "%20". if (urlArtist.contains(" ")) { urlArtist = urlArtist.replace(" ", "%20"); } if (urlAlbum.contains(" ")) { urlAlbum = urlAlbum.replace(" ", "%20"); } } //Construct the url for the HTTP request. URL uri = null; try { uri = new URL("http://itunes.apple.com/search?term=" + urlArtist + "+" + urlAlbum + "&entity=album"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return 1; } try { //Create a new HTTP connection. HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection(); urlConnection.connect(); //Set the destination directory for the xml file. File SDCardRoot = Environment.getExternalStorageDirectory(); file = new File(SDCardRoot, "albumArt.xml"); //Create the OuputStream that will be used to store the downloaded data into the file. FileOutputStream fileOutput = new FileOutputStream(file); //Create the InputStream that will read the data from the HTTP connection. InputStream inputStream = urlConnection.getInputStream(); //Total size of target file. int totalSize = urlConnection.getContentLength(); //Temp variable that stores the number of downloaded bytes. int downloadedSize = 0; //Create a buffer to store the downloaded bytes. byte[] buffer = new byte[1024]; int bufferLength = 0; //Now read through the buffer and write the contents to the file. while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; } //Close the File Output Stream. fileOutput.close(); } catch (MalformedURLException e) { //TODO Auto-generated method stub e.printStackTrace(); return 1; } catch (IOException e) { // TODO Auto-generated method stub e.printStackTrace(); return 1; } //Create a File object that points to the downloaded file. File phpSource = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/albumArt.xml"); String phpAsString = null; try { phpAsString = FileUtils.readFileToString(phpSource); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return 1; } //Extract the albumArt parameter from the PHP response. artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl100\":\"", "\","); if (artworkURL == null) { //Check and see if a lower resolution image available. artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl60\":\"", "\","); if (artworkURL == null) { URL_RETRIEVED = false; return 1; } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); URL_RETRIEVED = true; } } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); URL_RETRIEVED = true; } //Loop through the songs table and retrieve the data paths of all the songs (used to embed the artwork). //Replace any rogue apostrophes. if (album.contains("'")) { album = album.replace("'", "''"); } if (artist.contains("'")) { artist = artist.replace("'", "''"); } String selection = DBAccessHelper.SONG_ALBUM + "=" + "'" + album + "'" + " AND " + DBAccessHelper.SONG_ARTIST + "=" + "'" + artist + "'"; String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH }; Cursor cursor = mApp.getDBAccessHelper().getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE, projection, selection, null, null, null, null); if (cursor.getCount() != 0) { cursor.moveToFirst(); dataURIsList.add(cursor.getString(1)); while (cursor.moveToNext()) { dataURIsList.add(cursor.getString(1)); } } cursor.close(); if (URL_RETRIEVED == true) { artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL); File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg"); //Display the album art on the grid/listview so that the user knows that the download is complete. publishProgress(); //Save the artwork. try { FileOutputStream out = new FileOutputStream(artworkFile); artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); return 1; } finally { for (int i = 0; i < dataURIsList.size(); i++) { if (dataURIsList.get(i) != null) { File audioFile = new File(dataURIsList.get(i)); AudioFile f = null; try { f = AudioFileIO.read(audioFile); } catch (CannotReadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TagException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReadOnlyFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAudioFrameException e) { // TODO Auto-generated catch block e.printStackTrace(); } Tag tag = null; try { if (f != null) { tag = f.getTag(); } else { continue; } } catch (Exception e) { e.printStackTrace(); continue; } Artwork artwork = null; try { artwork = ArtworkFactory.createArtworkFromFile(artworkFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } if (artwork != null) { try { tag.setField(artwork); } catch (FieldDataInvalidException e) { // TODO Auto-generated catch block e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Exception e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } } try { f.commit(); } catch (CannotWriteException e) { // TODO Auto-generated catch block e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } //Update the album art tag in Jams' database. ContentValues values = new ContentValues(); String filePath = dataURIsList.get(i); filePath = filePath.replace("'", "''"); String where = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + filePath + "'"; values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, "byte://" + dataURIsList.get(i)); mApp.getDBAccessHelper().getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE, values, where, null); } else { continue; } } //Refresh the memory/disk cache for the ImageLoader instance. try { mApp.getImageLoader().clearMemoryCache(); mApp.getImageLoader().clearDiscCache(); } catch (Exception e) { e.printStackTrace(); } //Delete the temporary files once the artwork has been embedded. artworkFile.delete(); file.delete(); } } return 0; }
From source file:com.jelly.music.player.AsyncTasks.AsyncGetAlbumArtTask.java
@Override protected Integer doInBackground(String... params) { /************************************************************************************************ * RETRIEVE THE HTTP SEARCH RESPONSE FROM ITUNES SERVERS. ************************************************************************************************/ //First, we'll make a HTTP request to iTunes' servers with the album and artist name. if (params.length == 2) { artist = params[0];/*from w w w .j a v a 2 s . co m*/ album = params[1]; //Create duplicate strings that will be filtered out for the URL. urlArtist = artist; urlAlbum = album; //Remove any unacceptable characters. if (urlArtist.contains("#")) { urlArtist = urlArtist.replace("#", ""); } if (urlArtist.contains("$")) { urlArtist = urlArtist.replace("$", ""); } if (urlArtist.contains("@")) { urlArtist = urlArtist.replace("@", ""); } if (urlAlbum.contains("#")) { urlAlbum = urlAlbum.replace("#", ""); } if (urlAlbum.contains("$")) { urlAlbum = urlAlbum.replace("$", ""); } if (urlAlbum.contains("@")) { urlAlbum = urlAlbum.replace("@", ""); } //Replace any spaces in the artist and album fields with "%20". if (urlArtist.contains(" ")) { urlArtist = urlArtist.replace(" ", "%20"); } if (urlAlbum.contains(" ")) { urlAlbum = urlAlbum.replace(" ", "%20"); } } //Construct the url for the HTTP request. URL uri = null; try { uri = new URL("http://itunes.apple.com/search?term=" + urlArtist + "+" + urlAlbum + "&entity=album"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return 1; } try { //Create a new HTTP connection. HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection(); urlConnection.connect(); //Set the destination directory for the xml file. File SDCardRoot = Environment.getExternalStorageDirectory(); file = new File(SDCardRoot, "albumArt.xml"); //Create the OuputStream that will be used to store the downloaded data into the file. FileOutputStream fileOutput = new FileOutputStream(file); //Create the InputStream that will read the data from the HTTP connection. InputStream inputStream = urlConnection.getInputStream(); //Total size of target file. int totalSize = urlConnection.getContentLength(); //Temp variable that stores the number of downloaded bytes. int downloadedSize = 0; //Create a buffer to store the downloaded bytes. byte[] buffer = new byte[1024]; int bufferLength = 0; //Now read through the buffer and write the contents to the file. while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; } //Close the File Output Stream. fileOutput.close(); } catch (MalformedURLException e) { //TODO Auto-generated method stub e.printStackTrace(); return 1; } catch (IOException e) { // TODO Auto-generated method stub e.printStackTrace(); return 1; } //Create a File object that points to the downloaded file. File phpSource = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/albumArt.xml"); String phpAsString = null; try { phpAsString = FileUtils.readFileToString(phpSource); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return 1; } //Extract the albumArt parameter from the PHP response. artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl100\":\"", "\","); if (artworkURL == null) { //Check and see if a lower resolution image available. artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl60\":\"", "\","); if (artworkURL == null) { URL_RETRIEVED = false; return 1; } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); URL_RETRIEVED = true; } } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); URL_RETRIEVED = true; } //Loop through the songs table and retrieve the data paths of all the songs (used to embed the artwork). //Replace any rogue apostrophes. if (album.contains("'")) { album = album.replace("'", "''"); } if (artist.contains("'")) { artist = artist.replace("'", "''"); } String selection = DBAccessHelper.SONG_ALBUM + "=" + "'" + album + "'" + " AND " + DBAccessHelper.SONG_ARTIST + "=" + "'" + artist + "'"; String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH }; Cursor cursor = mApp.getDBAccessHelper().getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE, projection, selection, null, null, null, null); if (cursor.getCount() != 0) { cursor.moveToFirst(); dataURIsList.add(cursor.getString(1)); while (cursor.moveToNext()) { dataURIsList.add(cursor.getString(1)); } } cursor.close(); if (URL_RETRIEVED == true) { artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL); File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg"); //Display the album art on the grid/listview so that the user knows that the download is complete. publishProgress(); //Save the artwork. try { FileOutputStream out = new FileOutputStream(artworkFile); artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); return 1; } finally { for (int i = 0; i < dataURIsList.size(); i++) { if (dataURIsList.get(i) != null) { File audioFile = new File(dataURIsList.get(i)); AudioFile f = null; try { f = AudioFileIO.read(audioFile); } catch (CannotReadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TagException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReadOnlyFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAudioFrameException e) { // TODO Auto-generated catch block e.printStackTrace(); } Tag tag = null; try { if (f != null) { tag = f.getTag(); } else { continue; } } catch (Exception e) { e.printStackTrace(); continue; } Artwork artwork = null; try { artwork = ArtworkFactory.createArtworkFromFile(artworkFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } if (artwork != null) { try { tag.setField(artwork); } catch (FieldDataInvalidException e) { // TODO Auto-generated catch block e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Exception e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } } try { f.commit(); } catch (CannotWriteException e) { // TODO Auto-generated catch block e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } //Update the album art tag in jelly' database. ContentValues values = new ContentValues(); String filePath = dataURIsList.get(i); filePath = filePath.replace("'", "''"); String where = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + filePath + "'"; values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, "byte://" + dataURIsList.get(i)); mApp.getDBAccessHelper().getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE, values, where, null); } else { continue; } } //Refresh the memory/disk cache for the ImageLoader instance. try { mApp.getImageLoader().clearMemoryCache(); mApp.getImageLoader().clearDiscCache(); } catch (Exception e) { e.printStackTrace(); } //Delete the temporary files once the artwork has been embedded. artworkFile.delete(); file.delete(); } } return 0; }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
@Test public void testQueryResponse_HEAD() throws Exception { String query = "DESCRIBE <foo:bar>"; String location = TestServer.REPOSITORY_URL; location += "?query=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); // Request RDF/XML formatted results: conn.setRequestProperty("Accept", RDFFormat.RDFXML.getDefaultMIMEType()); conn.connect();//ww w . j av a 2s. com try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } assertEquals(RDFFormat.RDFXML.getDefaultMIMEType(), contentType); assertEquals(0, conn.getContentLength()); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {/*from w w w.j a v a 2 s . co m*/ connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java
/** * Download File from Url in Folder; this method do the same thing that ServerPolling task does, * but i can't call another AsyncTask from class that is not main context. * * @param url/*from w ww. j a v a 2 s . com*/ * @param folder */ private Boolean downloadFileUrl(String url, File folder) { InputStream input = null; OutputStream output = null; String baseName = FilenameUtils.getBaseName(url); String extension = FilenameUtils.getExtension(url); Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension); boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } HttpURLConnection connection = null; if (!f.isUrl(url)) return false; Boolean downloadSuccess = false; try { URL Url = new URL(url); connection = (HttpURLConnection) Url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if ((!url.endsWith(".csv") || !url.endsWith(".txt")) && connection.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.e(TAG, "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()); return false; } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling with back button if (isCancelled()) { input.close(); return false; } total += count; output.write(data, 0, count); downloadSuccess = true; } } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return true; }
From source file:com.hly.component.download.DownloadTransaction.java
public void run() { // TODO ?Daemon InputStream is = null;/* ww w . j a v a2 s . c o m*/ HttpURLConnection conn = null; RandomAccessFile randomFile = null; File tmpFile = null; try { // ?uri tmpFile = new File(mTempLocalUri); File parentFile = tmpFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!tmpFile.exists()) { tmpFile.createNewFile(); } randomFile = new RandomAccessFile(mTempLocalUri, "rw"); long fileLength = randomFile.length(); completeSize = fileLength; if (isCancel) { return; } String connUrl = mUri; // ?uri???? // getRedirectUrl(connUrl); if (!T.ckIsEmpty(mRedirectUri)) { connUrl = mRedirectUri; } conn = getHttpConnetion(connUrl); conn.setRequestProperty("range", "bytes=" + fileLength + "-"); conn.connect(); int contentLength = conn.getContentLength(); totalSize = completeSize + contentLength; if (contentLength == -1 || contentLength > 0) { // randomFile.seek(fileLength); byte[] buffer = new byte[8192]; is = conn.getInputStream(); int length = -1; while ((length = is.read(buffer)) != -1) { if (isCancel) { return; } randomFile.write(buffer, 0, length); completeSize += length; notifyProgress(length); } } mTransactionState.setState(TransactionState.SUCCESS); } catch (Throwable t) { Log.w(TAG, Log.getStackTraceString(t)); } finally { isRunning = false; isCancel = false; try { if (randomFile != null) { randomFile.close(); } } catch (IOException e) { e.printStackTrace(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (conn != null) { conn.disconnect(); } if (mTransactionState.getState() != TransactionState.SUCCESS) { mTransactionState.setState(TransactionState.FAILED); Log.e(TAG, "Delivery failed."); } else { if (tmpFile == null) { mTransactionState.setState(TransactionState.FAILED); } else { File localFile = new File(this.mLocalUri); boolean flag = tmpFile.renameTo(localFile); if (flag) { Log.d(TAG, "rename pic succ" + this.mLocalUri); } else { mTransactionState.setState(TransactionState.FAILED); Log.d(TAG, "rename pic failed" + this.mLocalUri); } } } notifyObservers(); } }
From source file:blueprint.sdk.google.gcm.GcmSender.java
/** * decodes response from GCM//from w w w .j a va 2 s. c o m * * @param http HTTP connection * @return response from GCM * @throws IOException */ @SuppressWarnings("ResultOfMethodCallIgnored") private GcmResponse decodeResponse(HttpURLConnection http) throws IOException { GcmResponse result = new GcmResponse(); result.code = getResponseCode(http); if (result.code == HttpURLConnection.HTTP_OK) { try { Response response = mapper.readValue((InputStream) http.getContent(), Response.class); result.multicastId = response.multicast_id; result.success = response.success; result.failure = response.failure; result.canonicalIds = response.canonical_ids; // decode 'results' for (Map<String, String> item : response.results) { GcmResponseDetail detail = new GcmResponseDetail(); if (item.containsKey("message_id")) { detail.success = true; detail.message = item.get("message_id"); } else { detail.success = false; detail.message = item.get("error"); } result.results.add(detail); } } catch (Exception e) { result.code = GcmResponse.ERR_JSON_BIND; L.warn("Can't bind json", e); } } else if (result.code == GcmResponse.ERR_NOT_JSON) { int contentLength = http.getContentLength(); String contentType = http.getContentType(); InputStream ins = (InputStream) http.getContent(); byte[] buffer = new byte[contentLength]; ins.read(buffer); L.warn("response message is not a json. content-type=" + contentType + ", content=" + new String(buffer)); } return result; }
From source file:com.miz.functions.MizLib.java
public static int getFileSize(URL url) { HttpURLConnection conn = null; try {// w ww . j a v a2 s. c o m conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); return conn.getContentLength(); } catch (IOException e) { return -1; } finally { conn.disconnect(); } }