List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:pt.ieeta.jlay.jlay.agent.DataStream.java
public MessageI getData(String id) { String url = GlobalSettings.getHTTPServerRootURL() + "getMessage?id=" + id; try {//from w w w.ja v a 2s.co m URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedInputStream in = new BufferedInputStream(con.getInputStream()); System.out.println("connection lenght "); System.out.println(con.getContentLength()); byte[] r = new byte[con.getContentLength()]; in.read(r); in.close(); System.out.println(r); System.out.println(r.length); GeneralMessage g = SerializationUtils.deserialize(r); return g; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:eu.krawczyk.shutterstocktask.services.DownloadService.java
@Override protected void onHandleIntent(Intent intent) { String urlPath = intent.getStringExtra(URL); String name = intent.getStringExtra(NAME); File output = new File(Environment.getExternalStorageDirectory(), name); // check if output directory exists if (output.exists()) { output.delete();// ww w.j a v a 2s .c o m } InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { URL url = new URL(urlPath); fileOutputStream = new FileOutputStream(output.getPath()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.e(Constants.General.TAG, "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()); mResult = EDownloadStatus.FAILED.ordinal(); } else { prepareNotification(); int fileLength = connection.getContentLength(); inputStream = connection.getInputStream(); byte data[] = new byte[BUFFER_SIZE]; long total = 0; int count; while ((count = inputStream.read(data)) != -1 && mIsCancelled == false) { total += count; // publishing the progress.... if (fileLength > 0) { updateNotification((int) (total * 100 / fileLength)); } fileOutputStream.write(data, 0, count); } // finished if (mIsCancelled == true) { mResult = EDownloadStatus.CANCELLED.ordinal(); // Reset mIsCancelled flag mIsCancelled = false; } else { mResult = EDownloadStatus.SUCCESS.ordinal(); } updateNotification(MAX_PROGRESS); } } catch (Exception e) { Log.e(Constants.General.TAG, "Exception while downloading image: " + e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(Constants.General.TAG, "Exception while closing stream: " + e); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { Log.e(Constants.General.TAG, "Exception while closing stream: " + e); } } } publishResults(output.getAbsolutePath(), mResult, 100); }
From source file:org.apache.cordova.plugins.DownloadManager.Downloader.java
public Boolean run() throws InterruptedException, JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { NotificationManager mNotifyManager; NotificationCompat.Builder mBuilder; Intent intent;/*from w w w. j av a 2 s. com*/ PendingIntent pend; int mNotificationId; Log.d("PhoneGapLog", "dirName: " + dirName); Log.d("PhoneGapLog", "fileName: " + fileName); try { File dir = new File(dirName); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dirName, fileName); if (file.exists() && !overwrite) { String temp_filename; int i; for (i = 1;; i++) { // test.txt -> test_1.txt -> test_2.tx -> ... while(file.exists()) temp_filename = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + String.valueOf(i) + fileName.substring(fileName.lastIndexOf('.')); file = new File(dirName, temp_filename); if (!file.exists()) { fileName = temp_filename; break; } } } else if (file.exists() && overwrite) { file.getCanonicalFile().delete(); //Delete file = new File(dirName, fileName); //Declare the same } intent = new Intent(); intent.putExtra("cancel_download", 1); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pend = PendingIntent.getActivity(cordova.getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mNotifyManager = (NotificationManager) cordova.getActivity() .getSystemService(Activity.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(cordova.getActivity()) /*.setSmallIcon(android.R.drawable.ic_stat_notification)*/ .setContentTitle(notificationTitle) /*.setSubText("Tap to CANCEL")*/ .setTicker(ticker).setContentIntent(pend).setContentText("0% - " + fileName); mNotificationId = new Random().nextInt(10000); URL url = new URL(fileUrl); HttpURLConnection ucon = (HttpURLConnection) url.openConnection(); ucon.setRequestMethod("GET"); ucon.connect(); InputStream is = ucon.getInputStream(); byte[] buffer = new byte[1024]; int readed = 0, progress = 0, totalReaded = 0, fileSize = ucon.getContentLength(); // First Notification (id to Javascript) (not necessary necessary): informProgress(id, true, fileSize, 0, dirName, fileName, callbackContext); FileOutputStream fos = new FileOutputStream(file); showToast(startToast, "short"); int step = 0; while ((readed = is.read(buffer)) > 0 && downloading_ids.isId(id)) { fos.write(buffer, 0, readed); totalReaded += readed; int newProgress = (int) (totalReaded * 100 / fileSize); if (newProgress != progress & newProgress > step) { if (useNotificationBar) { mBuilder.setProgress(100, newProgress, false); mBuilder.setContentText(step + "% - " + fileName); mBuilder.setContentIntent(pend); mNotifyManager.notify(mNotificationId, mBuilder.build()); } informProgress(id, true, fileSize, step, dirName, fileName, callbackContext); step = step + 1; } } // Download canceled?? if (!downloading_ids.isId(id)) { showToast(cancelToast, "short"); fos.flush(); fos.close(); is.close(); ucon.disconnect(); if (useNotificationBar) { mBuilder.setContentText("Download of \"" + fileName + "\" canceled").setProgress(0, 0, false); mNotifyManager.notify(mNotificationId, mBuilder.build()); try { Thread.sleep(1000); } catch (InterruptedException e) { Log.d("PhoneGapLog", "Downloader Plugin: Thread sleep error: " + e); } mNotifyManager.cancel(mNotificationId); } // Delete file: file.getCanonicalFile().delete(); callbackContext.sendPluginResult( new PluginResult(PluginResult.Status.OK, "Download properly canceled")); } else { // Download Normal END (continue) if (useNotificationBar) { mBuilder.setContentText("Download of \"" + fileName + "\" completed").setProgress(0, 0, false); mNotifyManager.notify(mNotificationId, mBuilder.build()); } showToast(endToast, "short"); informProgress(id, false, fileSize, step, dirName, fileName, callbackContext); downloading_ids.del(id); } fos.flush(); fos.close(); is.close(); ucon.disconnect(); mNotifyManager.cancel(mNotificationId); if (!file.exists()) { showToast("Download went wrong, please try again or contact the developer.", "long"); Log.e("PhoneGapLog", "Downloader Plugin: Error: Download went wrong."); } //callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } catch (FileNotFoundException e) { showToast( "File does not exists or cannot connect to webserver, please try again or contact the developer.", "long"); Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR); e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); } catch (IOException e) { showToast("Error downloading file, please try again or contact the developer.", "long"); Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR); e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); } catch (JSONException e) { e.printStackTrace(); callbackContext .sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage())); } catch (InterruptedException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); } } }); return true; }
From source file:org.wso2.carbon.integration.common.tests.DistributionValidationTest.java
@Test(groups = "wso2.all", description = "Comparison of distribution sizes", dependsOnMethods = "testMavenVariablesReplacement") public void testCompareDistributionSize() throws ParserException, IOException { double runningDistributionSize; double mavenDistributionSize = 0; boolean mavenDistributionStatus = false; boolean sizeDifferenceStatus = false; String path;/* w w w . j a va 2 s. c om*/ String productName = distributionVersion.getName().split("wso2")[1].split("-")[0]; if (productName.contains("as")) { path = "appserver" + File.separator + "wso2as" + File.separator; } else { path = productName + File.separator + "wso2" + productName + File.separator; } String urlToDistributionList = "http:" + File.separator + File.separator + "maven.wso2.org" + File.separator + "nexus" + File.separator + "content" + File.separator + "repositories" + File.separator + "wso2maven2" + File.separator + "org" + File.separator + "wso2" + File.separator + path; List<String> linksToVersion = DistributionValidationTestUtils.getLinks(urlToDistributionList); List<String> linksFromVersion = DistributionValidationTestUtils .getLinks(linksToVersion.get(linksToVersion.size() - 1)); URL url = null; for (Object link : linksFromVersion) { String temp = link.toString(); if (temp.contains(".zip") && !temp.contains(".zip.")) { url = new URL(temp); break; } } HttpURLConnection conn; if (url != null) { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); mavenDistributionSize = conn.getContentLength(); mavenDistributionStatus = true; conn.disconnect(); } assertTrue("Either no product distribution detected in the maven repo " + "or connection establishment failure", mavenDistributionStatus); File distributionFile = new File(System.getProperty("carbon.zip")); //calculating the running zip file size runningDistributionSize = distributionFile.length(); HashMap<String, String> resultsDataMap = new HashMap<String, String>(); DecimalFormat df = new DecimalFormat("#.00"); String runningDistribution = df.format(runningDistributionSize / (1024 * 1024)); String mavenDistribution = df.format(mavenDistributionSize / (1024 * 1024)); String difference = df.format((mavenDistributionSize - runningDistributionSize) / (1024 * 1024)); resultsDataMap.put("Running Distribution Size", runningDistribution + " MB"); resultsDataMap.put("Maven Distribution Size", mavenDistribution + " MB"); resultsDataMap.put("The difference between running distribution and maven distribution" + " sizes are ", difference + " MB"); // checking whether size of the running distribution is acceptable if (Double.parseDouble(difference) >= 20) { DistributionValidationTestUtils.reportGeneratorMap(resultsDataMap, "Running distribution size " + "comparison failure.Below are the sizes of two packs compared.", reportFile); sizeDifferenceStatus = true; } else { DistributionValidationTestUtils.reportGeneratorMap(resultsDataMap, "Running distribution size comparison passed." + " Below are the sizes of two packs compared.", reportFile); } assertFalse("Running Distribution size exceeds the acceptable limit size range " + "compared to the previous released distribution size", sizeDifferenceStatus); }
From source file:com.example.gtuandroid.component.ImageDownloader.java
Bitmap downloadBitmap(String url) { Bitmap webImg = null;/*from ww w .j av a 2 s . co m*/ try { URL imgUrl = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) imgUrl.openConnection(); httpURLConnection.connect(); InputStream inputStream = httpURLConnection.getInputStream(); int length = httpURLConnection.getContentLength(); int tmpLength = 512; int readLen = 0, desPos = 0; byte[] img = new byte[length]; byte[] tmp = new byte[tmpLength]; if (length != -1) { while ((readLen = inputStream.read(tmp)) > 0) { System.arraycopy(tmp, 0, img, desPos, readLen); desPos += readLen; } webImg = BitmapFactory.decodeByteArray(img, 0, img.length); if (desPos != length) { throw new IOException("Only read" + desPos + "bytes"); } } httpURLConnection.disconnect(); } catch (IOException e) { Log.e("IOException", e.toString()); } return webImg; }
From source file:de.uni.stuttgart.informatik.ToureNPlaner.Net.Handler.SyncCoreLoader.java
private InputStream readCoreFileFromNetAndCache() throws IOException { HttpURLConnection con = null; try {/*from w w w .ja v a 2s . com*/ URL url = new URL(coreURL + pathPrefix + corePrefix + coreLevel + coreSuffix); con = (HttpURLConnection) url.openConnection(); File cacheDirFile = ToureNPlanerApplication.getContext().getExternalCacheDir(); Log.d(TAG, "Trying to download core to " + cacheDirFile.getAbsolutePath() + corePrefix + coreLevel + coreSuffix); FileOutputStream coreFileStream = new FileOutputStream( new File(cacheDirFile, corePrefix + coreLevel + coreSuffix)); Log.d(TAG, "Content-Length: " + con.getContentLength()); InputStream in = new BufferedInputStream(con.getInputStream()); TeeInputStream teeStream = new TeeInputStream(in, coreFileStream, true); return teeStream; } catch (MalformedURLException e) { e.printStackTrace(); if (con != null) { con.disconnect(); } return null; } }
From source file:org.csware.ee.utils.Tools.java
public static String GetDataByPost(String httpUrl, String parMap) { try {/*from w ww . j a v a 2 s.c om*/ URL url = new URL(httpUrl);// HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // ? connection.setRequestProperty("Accept", "application/json"); // ?? connection.setRequestProperty("Content-Type", "application/json"); // ???? connection.connect(); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8? out.append(parMap); out.flush(); out.close(); // ?? int length = (int) connection.getContentLength();// ? InputStream is = connection.getInputStream(); if (length != -1) { byte[] data = new byte[length]; byte[] temp = new byte[1024]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, "UTF-8"); // utf-8? return result; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("aa: " + e.getMessage()); } return "error"; // ? }
From source file:org.peterbaldwin.vlcremote.sweep.Worker.java
@Override public void run() { // Note: InetAddress#isReachable(int) always returns false for Windows // hosts because applications do not have permission to perform ICMP // echo requests. for (;;) {/*from ww w . j a v a 2 s . c o m*/ byte[] ipAddress = mManager.pollIpAddress(); if (ipAddress == null) { break; } try { InetAddress address = InetAddress.getByAddress(ipAddress); String hostAddress = address.getHostAddress(); URL url = createUrl("http", hostAddress, mPort, mPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1000); try { int responseCode = connection.getResponseCode(); String responseMessage = connection.getResponseMessage(); InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? connection.getInputStream() : connection.getErrorStream(); if (inputStream != null) { try { int length = connection.getContentLength(); InputStreamEntity entity = new InputStreamEntity(inputStream, length); entity.setContentType(connection.getContentType()); // Copy the entire response body into memory // before the HTTP connection is closed: String body = EntityUtils.toString(entity); ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1); String hostname = address.getHostName(); StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage); HttpResponse response = new BasicHttpResponse(statusLine); response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort); response.setEntity(new StringEntity(body)); mCallback.onReachable(ipAddress, response); } finally { inputStream.close(); } } else { Log.w(TAG, "InputStream is null"); } } finally { connection.disconnect(); } } catch (IOException e) { mCallback.onUnreachable(ipAddress, e); } } }
From source file:org.talend.librariesmanager.utils.nexus.NexusDownloader.java
@Override public void download(URL url, File desc) throws Exception { BufferedInputStream bis = null; BufferedOutputStream bos = null; File tempFolder = null;/*from w w w .j av a 2 s . c o m*/ try { TalendLibsServerManager manager = TalendLibsServerManager.getInstance(); final NexusServerBean talendlibServer = manager.getLibrariesNexusServer(); String mavenUri = url.toExternalForm(); MavenArtifact parseMvnUrl = MavenUrlHelper.parseMvnUrl(mavenUri); if (parseMvnUrl != null) { String reletivePath = PomUtil.getArtifactPath(parseMvnUrl); String tempPath = getTmpFolderPath(); File createTempFile = File.createTempFile("talend_official", ""); createTempFile.delete(); tempFolder = new File(tempPath + File.separator + createTempFile.getName()); if (tempFolder.exists()) { tempFolder.delete(); } tempFolder.mkdirs(); String name = parseMvnUrl.getArtifactId(); String type = parseMvnUrl.getType(); if (type == null || "".equals(type)) { type = MavenConstants.PACKAGING_JAR; } name = name + "." + type; File destination = new File(tempFolder, name); HttpURLConnection connection = getHttpURLConnection(talendlibServer.getServer(), talendlibServer.getRepositoryId(), reletivePath, talendlibServer.getUserName(), talendlibServer.getPassword()); InputStream inputStream = connection.getInputStream(); bis = new BufferedInputStream(inputStream); bos = new BufferedOutputStream(new FileOutputStream(destination)); int contentLength = connection.getContentLength(); fireDownloadStart(contentLength); int bytesDownloaded = 0; byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = bis.read(buf)) != -1) { bos.write(buf, 0, bytesRead); fireDownloadProgress(bytesRead); bytesDownloaded += bytesRead; if (isCancel()) { return; } } bos.flush(); bos.close(); if (bytesDownloaded == contentLength) { ArtifactsDeployer deployer = new ArtifactsDeployer(); deployer.deployToLocalMaven(destination.getAbsolutePath(), mavenUri); // update module status final Map<String, ELibraryInstallStatus> statusMap = ModuleStatusProvider.getStatusMap(); statusMap.put(mavenUri, ELibraryInstallStatus.INSTALLED); ModuleStatusProvider.getDeployStatusMap().put(mavenUri, ELibraryInstallStatus.DEPLOYED); } } fireDownloadComplete(); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (tempFolder != null) { FilesUtils.deleteFile(tempFolder, true); } } }
From source file:com.thx.bizcat.util.ImageDownloader.java
public Bitmap imageViewProcessing(String localImgUrl, String ServerImgUrl) { // 1. Cache Check Bitmap bm = getBitmapFromCache(localImgUrl); if (bm != null) return bm; // 2. File Check File file = new File(localImgUrl); if (file.exists()) { bm = BitmapFactory.decodeFile(file.getAbsolutePath()); if (bm != null) return bm; else//from ww w .ja v a 2 s. c o m file.delete(); } else { boolean b = file.mkdirs(); b = file.delete(); //b = dir.createNewFile(); } // 3. Download Image try { URL url = new URL(ServerImgUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(localImgUrl); int len = conn.getContentLength(); byte[] raster = new byte[len]; int read = 0; while (true) { read = is.read(raster); if (read <= 0) break; fos.write(raster, 0, read); } is.close(); fos.close(); conn.disconnect(); bm = BitmapFactory.decodeFile(localImgUrl); if (bm != null) return bm; } catch (Exception e) { e.printStackTrace(); } return null; }